如何在 PHP 中检查上传文件的文件类型? [英] How to check file types of uploaded files in PHP?

查看:48
本文介绍了如何在 PHP 中检查上传文件的文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 网站上,他们建议的唯一真正检查是使用 is_uploaded_file()move_uploaded_file()此处.当然,出于各种原因,您通常不希望用户上传任何类型的文件.

On the PHP website, the only real checking they suggest is using is_uploaded_file() or move_uploaded_file(), here. Of course you usually don't want user's uploading any type of file, for a variety of reasons.

因此,我经常使用一些严格"的 mime 类型检查.当然这是非常有缺陷的,因为通常 mime 类型是错误的,用户无法上传他们的文件.它也很容易伪造和/或更改.除此之外,每个浏览器和操作系统对它们的处理方式也不同.

Because of this, I have often used some "strict" mime type checking. Of course this is very flawed because often mime types are wrong and users can't upload their file. It is also very easy to fake and/or change. And along with all of that, each browser and OS deals with them differently.

另一种方法是检查扩展名,这当然比mime类型更容易更改.

Another method is to check the extension, which of course is even easier to change than mime type.

如果你只想要图片,使用像 getimagesize() 这样的东西就可以了.

If you only want images, using something like getimagesize() will work.

其他类型的文件呢?PDF、Word 文档或 Excel 文件?甚至纯文本文件?

What about other types of files? PDFs, Word documents or Excel files? Or even text only files?

如果您没有 mime_content_typeFileinfo 和 system("file -bi$uploadedfile") 给出了错误的文件类型,还有哪些其他选项?

If you don't have mime_content_type or Fileinfo and system("file -bi $uploadedfile") gives you the wrong file type, what other options are there?

推荐答案

看一看 mime_content_type文件信息.这些是内置的 PHP 命令,用于通过查看文件的内容来确定文件的类型.还检查了上面两页的评论,还有一些其他的好建议.

Take a look at mime_content_type or Fileinfo. These are built-in PHP commands for determining the type of a file by looking at the contents of the file. Also check the comments on the above two pages, there are some other good suggestions.

就我个人而言,使用本质上是 system("file -bi $uploadedfile") 的东西我很幸运,但我不确定这是否是最好的方法.

Personally I've had good luck using something that's essentially system("file -bi $uploadedfile"), but I'm not sure if that's the best method.

这篇关于如何在 PHP 中检查上传文件的文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆