Php 如何验证$#u FILES[';userfile';][';type';]提供的mime类型

Php 如何验证$#u FILES[';userfile';][';type';]提供的mime类型,php,image,file-upload,mime-types,Php,Image,File Upload,Mime Types,我当时正在阅读的文档如下: $\u文件['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however NOT checked on the PHP side and therefore don't take its value for gra

我当时正在阅读的文档如下:

$\u文件['userfile']['type']

The mime type of the file, if the browser provided this information. An example 
would be "image/gif". This mime type is however NOT checked on the PHP side 
and therefore don't take its value for granted.
那么,如何验证文件是否为正确的mime类型,以防止用户将可能有害的文件上载到服务器;或者在服务器端执行的代码中导致错误(因为我可能会尝试在不是真正的jpeg图像的文件上使用仅限jpeg的函数)


提前感谢

您可以使用
finfo_文件
了解PHP认为该文件是什么类型。然而,我认为这也不可靠。我相信它使用启发式,它不会扫描整个文件以确保它完全有效。例如,如果它以类似
的内容开头,它会说它是
文本/html
,它不会解析整个内容以确保它是正确的。

您可以使用
finfou file
来找出PHP认为该文件是什么类型的。然而,我认为这也不可靠。我相信它使用启发式,它不会扫描整个文件以确保它完全有效。例如,如果它以类似
的内容开头,它会说它是
文本/html
,它不会解析整个内容以确保它是正确的

    function getMimeType()
        {

                $finfo = new finfo(FILEINFO_MIME);
                $type = $finfo->file($_FILES['field_name']['tmp_name']);//change the field_name
                $mime = substr($type, 0, strpos($type, ';'));
                return $mime;

        }

        function isValidImage()
        {

            $mime = getMimeType();
            if(stristr($mime,'image'))
                return true;
            else 
                return false;

        }
        $res=isValidImage();
试试这个,它也会检查mime

试试这个,它也会检查mime