Image Proxy Script

Posted By: Ian on Mar 28, 2012 in PHP, Snippets
Last modified on December 9th, 2012 at 8:01 pm,

If you want to hide the location from which your serving your images from then you need an Image Proxy Script like this.
This script utilises several built in php functions:-

Lets say you have an image upload script where you let your “untrusted” users upload images to your site and you want to make sure they are actually uploading images and nothing else what do you need todo?

Well this script does 3 things

  1. Checks the image is coming from the same site as the script
  2. Checks the image actually has size and so is an image
  3. Reads the file rather than executes it
<?php

/**
 * The absolute path to the image folder
 */
$imgLocation = '/home/username/img/';

/**
 * This fetches a file name from the URL in this example it's holiday.jpg
 * http://yoursite.com/fetch.php?image=holiday.jpg
 * The "basename" function is there for security, to make sure
 * only a filename is passed, not a path.
 */
$imgName = basename($_GET['image']);
 
/**
 * Construct the actual image path.
 */
$imgPath = $imgLocation . $imgName;
 
/**
 * Make sure the file exists if not kill the script
 */
if(!file_exists($imgPath) || !is_file($imgPath)) {
    header('HTTP/1.0 404 Not Found');
    die('The file does not exist');
}
 
/**
 * Make sure the file is an image if not kill the script
 */
$imgData = getimagesize($imgPath);
if(!$imgData) {
    header('HTTP/1.0 403 Forbidden');
    die('The file you requested is not an image.');
}
 
/**
 * Set the appropriate content-type and provide the content-length.
 */
header('Content-type: ' . $imgData['mime']);
header('Content-length: ' . filesize($imgPath));
 
/**
 * Print the image data
 */
readfile($imgPath);



/**
 * Example usage
 *
 * http://yoursite.com/fetch.php?image=holiday.jpg 
 * <img src="fetch.php?image=max.jpg" alt="Max the Cat">
 * <img src="fetch.php?image=willy.jpg" alt="Willy the whale">
 */

?>

Original http://bytes.com/topic/php/answers/886538-retrieve-images-located-outside-web-root-using-php

Do you have any suggestions to improve this script? If so please post below.

AnonymousIan.J.Gough

Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125