Validating image uploads with PHP
I have an image upload program setup that I made with PHP to allow the public to submit their images. I am having trouble finding a method to make sure the file is actually an image. I'm checking the file type, and also using getimagesize(), amongst other checks but if I rename a text file to become a JPG file my validation allows the file. How can I ensure this is actually an ima开发者_如何学运维ge? I don't want my boss to execute any infected files.
you can use Imagick's identifyImage() command.
if it gives you back image data its an image if it hands back an error or no image data then its not an image. there is a command line version of this tool you can use to: http://www.imagemagick.org/script/identify.php if you do not have php compiled with imagemagick
Check allowed extensions
.gif .jpg .jpeg .png should be allowed
How about to use Exif module's exit-imagetype() function?
http://www.php.net/manual/en/function.exif-imagetype.php
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
?>
Reproduce the uploaded image using gd. If the image isn't reproduced, it's not an image!
If this function returns false, then it's not a valid image. I haven't worked with any more than jpg, png and gif, so there might be some more image types out there that can fit into this function (bmp?)...
function checkFileType($filetype,$tmp_name)
{
$return_val = false;
switch($filetype){
case 'image/jpg':
case 'image/jpeg':
case 'image/pjpeg':
$return_val = @imagecreatefromjpeg($tmp_name);
break;
case 'image/gif':
$return_val = @imagecreatefromgif($tmp_name);
break;
case 'image/png':
case 'image/x-png':
$return_val = @imagecreatefrompng($tmp_name);
break;
}
return $return_val;
}
精彩评论