更新时间:2023-09-29 22:06:58
您应该将文件的 tmp_name* 传递给 getimagesize,它会给你图片的大小和类型(如果是图片).如果传递的参数是文件而不是图像,则返回 false,这将允许您进行验证.
You should pass the tmp_name of the file* to getimagesize, it will give you the size and type of the image (if it is an image). If the passed argument is a file but not an image it returns false, that will allow you to validate.
图像验证唯一可靠的方法是使用 GD 或 Imagick 制作它的副本 - getimagesize 很容易被黑.
The only reliable method of image validation is to make a copy of it using GD or Imagick - getimagesize can be easily hacked.
*:我的意思是上传后创建的临时文件.
*: I mean, the temporal file created after upload.
例如:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = $_FILES['file']['tmp_name'];
if (file_exists($file))
{
$imagesizedata = getimagesize($file);
if ($imagesizedata === FALSE)
{
//not image
}
else
{
//image
//use $imagesizedata to get extra info
}
}
else
{
//not file
}
}
此代码使用 file_exists 只是为了通用.如果没有上传文件,您将获得 $_FILES['file']['size'] = 0
, $_FILES['file']['tmp_name'] = ''
和 $_FILES['file']['error'] = 4
.另请参阅is_readable.有关错误值,请参阅 文件上传错误解释,位于 php.net.
This code uses file_exists just to be general. In case no file were uploaded you would get $_FILES['file']['size'] = 0
, $_FILES['file']['tmp_name'] = ''
and $_FILES['file']['error'] = 4
. See also is_readable. For the error values see file upload errors explained at php.net.