Question: I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html.

My File Structure:

```
 - userimages
   image.jpg
   image2.jpg

 - public_html
   filetoserveimage.html

```

I tried linking to an image in the userimages folder like this:

```
<img src="../userimages/image.jpg">

```

But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!

Answer: 
Use an image relay script!

To serve a imagefile that is outside the public\_html folder you would have to do it by a php script. E.g make a image-relay.php that reads the image that is outside the public html...

```
<?php
header('Content-Type: image/jpeg');
$_file = 'myimage.jpg'; // or $_GET['img']
echo file_get_contents('/myimages/'.$_file);
?>

```

Now, $\_file could be a $\_GET parameter, but its absolutley important to validate the input parameter...

now you can make an `<img src="image-relay.php?img=flower.jpg">` to access a flower.jpg image that is located in /myimage/flower.jpg ...
If you are using Apache or lighttpd you can use the X-Sendfile header to send files that are not in the web root(provided you haven't changed the configuration of mod\_xsendfile).

To learn more about X-sendfile see this [site](http://codeutopia.net/blog/2009/03/06/sending-files-better-apache-mod_xsendfile-and-php/).

This solution is giving you the best possible performance as PHP doesn't send the file but the server does and therefore PHP can be exited while the files are being served.

Hope that helps.