I just saw this post by “jazz_snob” posted at PHPBuilder.com, suggesting a means to secure untrusted image files. The basic idea is to use PHP’s GD image functions to create a copy of the file. As doing so would decompose the specified file into GD’s native bitmap format, and then recompose it into the desired image file type, any embedded “nastiness” within the original file ought to be left behind. It could be implemented into a function something like:
<?php
/**
* Copy an image to help ensure it is not "infected"
* @author Charles Reace (www.charles-reace.com)
* @param string path to image file to be copied
* @return resource GD image resource, boolean false if error
*/
function secureImage($filePath)
{
$sizeData = getimagesize($filePath);
if($sizeData === false)
{
user_error(__FUNCTION__ . "(): Unable to get imsge data");
return false;
}
list($unused, $type) = explode('/', $sizeData['mime']);
switch($type)
{
case 'gif':
$fh = imagecreatefromgif($filePath);
break;
case 'png':
$fh = imagecreatefrompng($filePath);
break;
case 'jpeg':
$fh = imagecreatefromjpeg($filePath);
break;
default:
user_error(__FUNCTION__ . "(): Unsupported image type '$type'");
return false;
}
return $fh;
}
// Sample usage:
$fh = secureImage('bg.gif');
if(!$fh)
{
header('HTTP/1.0: 404 Not Found');
exit;
}
header('Content-Type: image/gif');
imagegif($fh);
If any of you readers happens to have access to an “infected” image file and a safe sandbox where you could test the above, I’d be very interested to know if it does, in fact, filter out the non-image virus or whatever is embedded, or at the very least reject it with an error.

Interesting, but I have one thing to say: you shouldn’t just test if the image is a gif, a png or a jpg. You should test if the GD library can actually open it. Here’s a little function I use in order to open images only if they are compatible with the GD version on the server:
function loadImage($path) {
if (!file_exists($path)) return false;
list(,,$imageType) = getImageSize($path);
if (!(imagetypes() & $imageType)) return false;
return imageCreateFromString(file_get_contents($path));
}
Oh, and why do you use list($unused, $type) when you can simply use list( , $type) ?
Hi, Znupi. Thanks for posting your function. I’ll have to take a closer look at it when I get a chance. Ultimately, I’d probably want to combine it with something akin to what I did to further limit the allowed image types, as I may not ultimately want to allow all types that my GD installation supports; but it’s definitely a good idea to ensure that GD supports any image type that I want to allow. :)
That would strip out all other embedded metadata too: JPEG EXIF data, PNG tEXt blocks.
Good point, Hayley. I guess that needs to factor into one’s decision whether or not to do such “sanitizing”.