我对这个主题的想法很简单:所有上传的图片都是邪恶的。
不仅因为它们可能包含恶意代码,还因为元标记。我知道爬虫浏览网络以使用隐藏的元标记查找一些受保护的图像,然后使用他们的版权。也许有点偏执,但由于用户上传的图片无法控制版权问题,我会认真考虑。
为了摆脱这些问题,我使用 gd 系统地将所有上传的图像转换为 png。这有很多优点:图像从最终的恶意代码和元标记中清除,我对所有上传的图像只有一种格式,我可以调整图像大小以符合我的标准,并且...... 我立即知道图片是否有效!如果图片无法打开转换(使用imagecreatefromstring不关心图片格式),则认为图片无效。
一个简单的实现可能如下所示:
function imageUploaded($source, $target)
{
// check for image size (see @DaveRandom's comment)
$size = getimagesize($source);
if ($size === false) {
throw new Exception("{$source}: Invalid image.");
}
if ($size[0] > 2000 || $size[1] > 2000) {
throw new Exception("{$source}: Too large.");
}
// loads it and convert it to png
$sourceImg = @imagecreatefromstring(@file_get_contents($source));
if ($sourceImg === false) {
throw new Exception("{$source}: Invalid image.");
}
$width = imagesx($sourceImg);
$height = imagesy($sourceImg);
$targetImg = imagecreatetruecolor($width, $height);
imagecopy($targetImg, $sourceImg, 0, 0, 0, 0, $width, $height);
imagedestroy($sourceImg);
imagepng($targetImg, $target);
imagedestroy($targetImg);
}
测试它:
header('Content-type: image/png');
imageUploaded('http://www.dogsdata.com/wp-content/uploads/2012/03/Companion-Yellow-dog.jpg', 'php://output');
这并不能完全回答你的问题,因为这与接受的答案是同一种黑客,但我给你我使用它的理由,至少 :-)