4

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?

Ben Harvey
  • 1,793
  • 2
  • 16
  • 23
  • 2
    Ben, Take a look at CodeIgniter legendary [Phil Sturgeon's idea](http://stackoverflow.com/a/1913743/1725764) ;) – Hashem Qolami Jan 15 '14 at 10:25
  • 1
    Argh! I knew after hours of useless googling something like that would come up! Nice to see it come from Phil himself! Thanks! – Ben Harvey Jan 15 '14 at 11:37

1 Answers1

4

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') ?>" />
Vidar Vestnes
  • 42,644
  • 28
  • 86
  • 100
  • This is a nice neat way of doing it. The only problem in my case is that the site already has images in the public assets folder. However, it'd be easy to modify the route to the private images (like `p/img/jpg/myimage.jpg` or something similar. I'll mark as the answer cos it's the closest thing to a built in Codeigniter method. – Ben Harvey Jan 31 '14 at 16:13