php $_FILES["file"]["type"] 和 end(explode(".", $_FILES["file"]["name"])) 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15605030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:35:15  来源:igfitidea点击:

What is the difference between $_FILES["file"]["type"] and end(explode(".", $_FILES["file"]["name"]))

phpfile

提问by nut

I use var_dump(@$_FILES['file']['type'])to test file type I uploaded

var_dump(@$_FILES['file']['type'])用来测试我上传的文件类型

First, I uploaded an exe filecalled "uninstall.exe", and it returned

首先,我上传了一个exe file名为“ uninstall.exe”,然后它返回

"string 'application/octet-stream' (length=24)"

Then, I renamed this file to uninstall.png, it returned

然后,我将此文件重命名为uninstall.png,它返回

string 'image/png' (length=9)

My conclusion is: $_FILES['file']['type'] only check file extension, not the original file type.

我的结论是:$_ FILES['file']['type'] 只检查文件扩展名,不检查原始文件类型。

The following code is from w3cschool:

以下代码来自w3cschool

$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))

I think $_FILES["file"]["type"]in above codes is unnecessary, we can just check file extension using explode()and in_array

我认为$_FILES["file"]["type"]上面的代码是不必要的,我们可以使用explode()和检查文件扩展名in_array

I'm just a php beginner, can someone confirm my idea? Thanks!

我只是一个 php 初学者,有人可以证实我的想法吗?谢谢!

采纳答案by icktoofay

You're absolutely correct. The MIME type is provided by the client and you cannot guarantee it is cor­rect. For that matter, so is the file extension. If you need to be completely sure, you need to look at the file contents.

你是完全正确的。MIME 类型由客户端提供,您不能保证它是正确的。就此而言,文件扩展名也是如此。如果您需要完全确定,则需要查看文件内容。

回答by darthmaim

If you want to be sure that an image was uploaded, use getimagesize, that returns 0 for non-images.

如果您想确保图像已上传,请使用getimagesize,它为非图像返回 0。

回答by Lucas Freitas

You should be using a wrapper of GD or Imagick extensions. A very good one is WideImage.

您应该使用 GD 或 Imagick 扩展的包装器。一个非常好的是WideImage