gecko on wall
13 November 2007

Image Wrapper (PHP)

On a project I wanted users to upload image outside of the web tree (for an added level of security) and then have them be able to show them on a web page. So I had to write a simple PHP wrapper.

So here are two examples, they are in my web tree, but you can see the process.

Real locations are:

Fake locations are:

Please note I am explaining little bits. You will have to download entire code to get this working. It’s well commented.

Step 1: Routing

Route all files through your image wrapper script. This is done with the magic of .htaccess . I am not going to explain it, as many people have done it better, but basically it just takes a request and sends it to my index.php file

grab source: htaccess.txt

Step 2: Parse URL

Basically we grab the requested URL

//parse url into parts
$parts = @parse_url($_SERVER['REQUEST_URI']);

Next we grab the image path

$web_path = '/external/image-wrapper/';
// drop multiple slashes
$uri_path = preg_replace('#/+#', '/', $parts['path']);
// drop trailing slashes
$uri_path = preg_replace('#/$#', '', $uri_path);
// drop site path
$path = trim(preg_replace('#^'.$web_path.'#', '', $uri_path)); 	

This takes this “/external/image-wrapper/i/10t.jpg” and just makes is “i/10t.jpg”;

Step 3: Send correct place

There are probably many ways to this, but basically i set up an array of regular expressions and see what it matches and send correct place.

//image handlers
$pages = Array(
	//( /i/image_name)
	'#^i/([^/]+)$#' => 'do_image',
	//( /image/image_name)
	'#^image/([^/]+)$#' => 'do_image_other'
foreach ($pages as $page_pattern => $the_func)
	if (preg_match($page_pattern, $path, $matches))
		//call function

Step 4: Check image

//get info about image
$image_info = pathinfo($img_dir.$img_name);
//has name
//has extension
@isset($image_info['extension']) &&
//has basename
@isset($image_info['basename']) &&
//valid extension
isset( $ext_list[ strtolower( $image_info['extension'] ) ] ) &&
//real file
file_exists($img_dir.$image_info['basename'] )

Step 5: Send image

//set correct header
$contentType = 'Content-type: '.$ext_list[ $image_info['extension'] ];
header ($contentType);
//send file to browser


As mentioned i used this to get around images not being in the web tree, but there are other things you could do



Site has been moved is no longer being updated. Please head over to for new content