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

Joh*_*ohn 35 php file-upload

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

$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;
}
Run Code Online (Sandbox Code Playgroud)

但有些用户抱怨他们在上传任何类型的图片时出错,而其他一些用户则没有收到任何错误!

我想知道这是否解决了这个问题:

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

任何意见?

dec*_*eze 80

切勿使用$_FILES..['type'].其中包含的信息根本不会被验证,它是用户定义的值.自己测试类型.对于图像,exif_imagetype通常是一个不错的选择:

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

或者,如果您的服务器支持它们,那么finfo功能很棒.

  • exif_imagetype 是不可欺骗的吗? (2认同)

fee*_*ela 9

除了@deceze之外,您还可以使用finfo()来检查非图像文件的MIME类型:

$finfo = new finfo();
$fileMimeType = $finfo->file($path . $filename, FILEINFO_MIME_TYPE);
Run Code Online (Sandbox Code Playgroud)