如何检查安全的上传文件类型

How can I check type of uploaded file that's security

在 php 手册中说 $_FILES['userfile']['type'] 在客户端的控制下(所以我想也许它可以被编辑)。

php manual.

$_FILES['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.

还有这个:

You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side.



那么如何检查上传文件的类型来防止上传有害文件呢?

正如您自己发现的那样,您应该彻底检查每个文件以避免安全问题。

主要取决于您要允许的文件类型。我将执行以下两个步骤:

1.检查内容类型。

这里没有什么可添加的,您已经在您的问题中发布了执行此操作的方法。但是,这是可以伪造的,所以请不要忘记....

2。验证文件内容。

您应该仔细检查文件内容。如果你正在处理图像,为了安全起见,你可以使用 phps 图像函数。

示例:

$x = getimagesize($_FILES['uploadfile']['tmp_name']);
if (isset($x)) {
    if($x['mime'] != 'image/gif' && $x['mime'] != 'image/jpeg') {
        echo 'Not a valid GIF or JPEG';
        exit(0);
    }
}