小编典典

如何在PHP中检查上传的文件类型

php

我用这段代码检查图像的类型,

$f_type=$_FILES['fupload']['type'];

if ($f_type== "image/gif" OR $f_type== "image/png" OR $f_type== "image/jpeg" OR $f_type== "image/JPEG" OR $f_type== "image/PNG" OR $f_type== "image/GIF")
{
    $error=False;
}
else
{
    $error=True;
}

但是有些用户抱怨上传任何类型的图像时都会出错,而另一些用户则没有错误!

我想知道这是否可以解决问题:

if (mime_content_type($_FILES['fupload']['type']) == "image/gif"){...

任何意见?


阅读 289

收藏
2020-05-26

共1个答案

小编典典

永远不要使用$_FILES..['type']。其中包含的信息完全未经验证,它是用户定义的值。自己测试类型。对于图像,exif_imagetype通常是一个不错的选择:

$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);

另外,如果您的服务器支持这些finfo功能,则它们的功能很棒。

2020-05-26