且构网

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

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

更新时间:2023-02-08 18:36:10

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

Never use $_FILES..['type']. The information contained in it is not verified at all, it's a user-defined value. Test the type yourself. For images, exif_imagetype is usually a good choice:

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

或者,finfo 函数 也很棒,如果您的服务器支持它们.

Alternatively, the finfo functions are great, if your server supports them.