Ben Harvey Ben Harvey -4 years ago 85
PHP Question

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:


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?

Answer Source

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

Simple example:

class Img extends CI_Controller {

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

Now you can point your img src to something like:

<img src="<?php echo base_url('img/jpg/myimage.jpg') ?>" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download