Image upload security - reprocess with GD

ⅰ亾dé卋堺 提交于 2019-11-28 01:53:16

问题


I've heard that the best way to handle uploaded images is to "re-process" them using the GD library and save the processed image. see: PHP image upload security check list

My question is how do this "re-processing" in GD? What this means exactly? I don't know the GD library very well and I'm afraid I will mess it up...

So if anyone who did this before could you give me an example for this?

(I know, another other option is to use ImageMagick. For ImageMagick I found an answer here: Remove EXIF data from JPG using PHP, but I can't use ImgMagick now. By the way.. removing EXIF data means completely recreate the image in this case?)
(I'm using Zend Framework if someone interested.)


回答1:


If the user uploads a JPEG file, you could do something like this to reprocess it:

$newIm = @imagecreatefromjpeg($_FILES['file']['tmp_name']);
if (!$newIm) {
    // gd could not create an image from the source
    // most likely, the file was not a valid jpeg image
}

You could then discard the $newIm image using imagedestroy() and use the uploaded file from the user, or save out the image from GD and use that. There could be some issues with saving the GD image as it is not the original image.

Another simple method would be to check the header (first several bytes) of the image file to make sure it is correct; for example all JPEG files begin with 0xff 0xd8.

See also imagecreatefromstring(), and you can also use getimagesize() to run similar checks on the uploaded image.




回答2:


function isvalidjpeg($file) 
{ 
$finfo = finfo_open(FILEINFO_MIME_TYPE);
return is_resource($finfo) && 
       (finfo_file($finfo, $file) === 'image/jpeg') && 
       finfo_close($finfo);
}
if(isvalidjpeg($_FILES['file']['tmp_name'])) {
   $newIm = @imagecreatefromjpeg($_FILES['file']['tmp_name']); .....


来源:https://stackoverflow.com/questions/9754047/image-upload-security-reprocess-with-gd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!