简体   繁体   English

在PHP中获取文件mime类型的最佳方法

[英]Best way to get a files mime typein PHP

What is the best way to get the mime type of a file? 获取文件的mime类型的最佳方法是什么? Before any answers are given, here are a list of a few things to consider. 在给出任何答案之前,这里列出了一些需要考虑的事项。

  1. Can't rely on upload form for accuracy 不能依靠上传表格来保证准确性
  2. Fileinfo has been inaccurate in 5.3 with testing 在测试中,Fileinfo在5.3中是不准确的
  3. mime_content_type has been inaccurate with test like FileInfo mime_content_type与FileInfo之类的测试一样不准确
  4. This goes beyond just image types so getImageSize() is not a viable option. 这不仅仅是图像类型,因此getImageSize()不是一个可行的选择。

Could this also be an apache/server/pear thing and not just rely on php functions? 这也可能是一个apache / server / pear的东西而不仅仅依赖于php函数吗?

Sad to say, there is no perfect way to do so in any programming language. 可悲的是,没有任何编程语言这样做没有完美的方法。

The 2 most standard way to get the minetype is 获得该类型的两种最标准的方法是

  1. Determine from the file extension... So something.jpg is a jpeg file and something.doc is a word document. 从文件扩展名确定...所以something.jpg是一个jpeg文件,something.doc是一个word文档。
  2. Determine from the magic string in the file... so if the first 2 bytes of the file is 0xFF 0xD8, it's a jpeg file. 从文件中的魔术字符串确定...所以如果文件的前2个字节是0xFF 0xD8,那么它是一个jpeg文件。 and a office document begins with 0xD0 0xCF 0x11 0xE0. 并且office文档以0xD0 0xCF 0x11 0xE0开头。

Both ways have pros and cons. 两种方式都有利有弊。

I can upload a exe file, but have it named with the extension of ".jpg" to defeat the first way or determining mime type. 我可以上传一个exe文件,但是以扩展名“.jpg”命名它以打败第一种方式或确定mime类型。

And for both types, I basically need a large database to search from so that i can tell what mimetype the file belongs to. 对于这两种类型,我基本上需要一个大型数据库来搜索,以便我可以告诉该文件属于哪种mimetype。

However, if you are only interested in determining the mimetype for a few types of files. 但是,如果您只对确定几种类型文件的mimetype感兴趣。 (Maybe just jpg, png, gif, etc), then the best way (imho) would be way number 2. Just keep a database or array of all the magic strings, and test the file against that. (也许只是jpg,png,gif等),然后最好的方式(imho)将是第2号方式。只需保留所有魔术字符串的数据库或数组,并针对该测试文件。

It is easy to get the magic strings, just Google. 很容易获得神奇的字符串,只有谷歌。

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

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