Displaying an image in php from a file in a directory

user396404 picture user396404 · Oct 26, 2010 · Viewed 10.1k times · Source

I have several images in a directory which is located outside of the public facing portion of the server (outside of the public_html directory). I want to be able to read the image contents with a php file, then output the result to html.

For example, I have a php file called getimg.php with the following source code:

header('Content-type: image/jpeg');

$dir = '/home/server/images/';
$file_name = addslashes($_GET['file']);

readfile('' . $dir . '' . $file_name . '.jpg');

getimg.php reads the contents of a jpg image in the images directory, then is referenced using the following code when I want to display the image to a user:

<img src="getimg.php?file=name_of_image_file">

The getimg.php file also does some verification checks to ensure that the user is logged in, actually owns the image they are trying to view, etc (this is not shown above for simplicity's sake). This approach is meant to control access to the image files. However, that is not the matter at hand.

Here is the problem: The approach/code above is only working in the Chrome browser. The images are not properly displaying in IE, FF, Safari, or Opera. Any ideas why this isn't working or how to do this properly?

Notes:

  • I am trying to avoid using mysql to store the images due to the large quantity of images. Being able to utilize the filesystem is greatly preferable here.

  • The solution must be cross browser friendly.

  • In reality, the image can be a jpg, png, or gif file. For the sake of simplicity, the above code only handles jpg images.

  • I doubt it is relevant, but I am NOT using jQuery. And no, I will not alter my entire site to use jQuery. Any "use jQuery" posts will automatically receive a downvote. I don't hate jquery.. it's just not the right solution for my site.

UPDATE

The problem was not with the code itself. I had my php.ini file set to auto include a login verification script. Since I was not logged in all of my browsers, the image was not displaying. Silly mistake, but understandable and fixed. The code above should work just fine. It has also been updated to use readfile() instead of file_get_contents(). I am going to leave this post up for anyone that's browsing the web looking for a way to control who has access to an image using php.

Answer

Decko picture Decko · Oct 26, 2010