Securing Uploaded Image Files
August 5, 2008 PHP 4 CommentsI 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.
