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

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

问题描述

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

因此,我经常使用一些严格的MIME类型检查。当然,这是非常有缺陷的,因为经常MIME类型是错误的,用户不能上传他们的文件。假冒和/或改变也很容易。除此之外,每个浏览器和操作系统都以不同的方式处理它们。另一种方法是检查扩展名,这比mime类型更容易更改。

如果您只需要图片,可以使用类似于 getimagesize()的图片。



其他类型的文件呢? PDF,Word文档或Excel文件?甚至文本只是文件?



编辑:如果您没有 mime_content_type

Fileinfo and system(file -bi $ uploadedfile)给你错误的文件类型, >解决方案

查看 mime_content_type

a>或 Fileinfo 。这些是内置的PHP命令,通过查看文件的内容来确定文件的类型。另外检查上面两页的评论,还有一些其他的好建议。

个人而言,我使用了一些本质上是 system(file -bi $ uploadedfile)的好运气,但我不确定这是否是最好的方法。


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.

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.

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

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

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

Edit: 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?

解决方案

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.

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天全站免登陆