且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查上传文件的最可靠方法是图像

更新时间:2023-11-25 17:26:28

finfo_*库会很好,但是它将与> = 5.3.0版本

finfo_* library would be good but it will work with >= 5.3.0 versions,

AND getimagesize() GD库函数,返回图像信息WxHsize

AND getimagesize() GD library function that is return image info WxH and size

如果图像无效,则getimagesize()显示警告,因此***使用finfo_*函数来验证图像

if image invalid then getimagesize() show warning so better to use to validate image using finfo_* function,

您也可以使用跨版本代码,请参见下面的示例代码

you can also do for cross version code, see below sample code

<?php 
$file = $_FILES['photo'];
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
$error = null;
if(function_exists('finfo_open')){    //(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
   $fileinfo = finfo_open(FILEINFO_MIME_TYPE);

    if (!in_array(finfo_file($fileinfo, $file['tmp_name']), $whitelist_type)) {
      $error[]  = "Uploaded file is not a valid image";
    }
}else if(function_exists('mime_content_type')){  //supported (PHP 4 >= 4.3.0, PHP 5)
    if (!in_array(mime_content_type($file['tmp_name']), $whitelist_type)) {
      $error[]  = "Uploaded file is not a valid image";
    }
}else{
   if (!@getimagesize($file['tmp_name'])) {  //@ - for hide warning when image not valid
      $error[]  = "Uploaded file is not a valid image";
   }
}