简体   繁体   English

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

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

In php manual said that $_FILES['userfile']['type'] is under control of the client(so maybe it can be edited,I guess). 在php手册中说$_FILES['userfile']['type']受客户端控制(所以我想也许可以对其进行编辑)。

php manual. PHP手册。

$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. 文件的MIME类型(如果浏览器提供了此信息)。
An example would be "image/gif". 一个例子是“ image / gif”。
This mime type is however not checked on the PHP side and therefore don't take its value for granted. 但是,不会在PHP端检查此mime类型,因此不要将其值视为理所当然。

and this: 和这个:

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. 您可以使用$_FILES['userfile']['type']变量丢弃不符合特定类型条件的所有文件,但只能将其用作一系列检查的第一步,因为该值完全在客户端的控制,而不是在PHP端进行检查。



So how can I check the type of uploaded file for preventing the harmful file to be uploaded? 那么,如何检查上传文件的类型以防止有害文件被上传?

As you've discovered for yourself, you should thoroughly check each file to avoid security issues. 正如您自己发现的那样,您应该彻底检查每个文件,以避免安全问题。

Mostly it depends on what kind of files you want to allow. 通常,这取决于您要允许哪种文件。 I'd go with these two steps: 我将遵循以下两个步骤:

1. Check the content type. 1.检查内容类型。

Nothing to add here, you've already posted the way to do it in your question. 在这里没有添加任何内容,您已经在问题中发布了完成此操作的方法。 However, this can be faked, so please don't forget to .... 但是,这可能是伪造的,所以请不要忘记...。

2. Verify the file content. 2.验证文件内容。

You should carefully check the files content. 您应该仔细检查文件内容。 If you're dealing with images, you can use phps image functions to be on the safe side. 如果要处理图像,则可以使用phps图像函数来确保安全。

Example: 例:

$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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM