Ben Harvey
Ben Harvey

Reputation: 1843

Serve image outside of webroot using codeigniter

I am using Codeigniter and am storing uploaded files outside the web root as a security precaution so that they or the upload folder are not directly accessible from the browser etc.

My structure is like this:

private
|_application
|_system
|_uploads
public_html
|_index.php

My question is, is there a Codeigniter function, similar to CakePHPs sendFile that I can use to serve up the images.

I know that I could store the images in the web root and limit the upload types to images, but I don't want to do that.

I also know that I could write an image.php style script that takes the file path and returns an image header, but before I go down that route, I wondered if there was a better/predefined way to do this with CodeIgniter specifically?

Upvotes: 4

Views: 2614

Answers (1)

Vidar Vestnes
Vidar Vestnes

Reputation: 42964

I would suggest you to make a controller with a function that handles image requests.

Simple example:

<?php
class Img extends CI_Controller {

    public function jpg($file)
    {
             // validate $file here, very important!
             $path = '../../uploads/' . $file;
             header('Content-type: image/jpeg');
             readfile($path);
    }
}
?>

Now you can point your img src to something like:

<img src="<?php echo base_url('img/jpg/myimage.jpg') ?>" />

Upvotes: 4

Related Questions