Script 11.5 Proxy PHP Example

Returns an image from the uploads directory based on the passed image name. Enables you to store your uploaded documents outside the web root directory for security reasons. If called without an image name - returns an empty page.

Output
Source
<?php # Script 11.5 - proxy - show_image.php
// This page displays an image from a directory outside of web root.

// Check for an image name in the URL, exclude any user submitted "../../../image" hacks :
if (isset($_GET['image']) && basename($_GET['image']) == $_GET['image']) {

	// Make sure it has an image's extension:
	$ext = strtolower ( substr ($_GET['image'], -4));
	$allowed = array('.jpg', '.gif', '.png', 'jpeg', '.JPG', '.GIF', '.PNG', 'JPEG');
	if(in_array($ext, $allowed)) {
		// Full image path:
		$image = UPLOAD_DIR."/{$_GET['image']}";

		// Check that the image exists and is a file:
		if (file_exists ($image) && (is_file($image))) {
			// Set the name as this image:
			$name = $_GET['image'];		
		} else {
			// If there was a problem, use the default image:
			$image = SITE_URL.'/images/unavailable.png';	
			$name = 'unavailable.png';
		} // End of file_exists() IF.
		// Get the image information:
		$info = getimagesize($image);
		$fs = filesize($image);
		// Send the content information:
		header ("Content-Type: {$info['mime']}\n");
		header ("Content-Disposition: inline; filename=\"$name\"\n");
		header ("Content-Length: $fs\n");

		// Send the file:
		readfile ($image);
	} // End of $ext IF.	
} // End of isset($_GET['image']) IF.