简体   繁体   English

检测 PHP 中的 MIME 类型

[英]Detecting MIME type in PHP

I'm looking for the best (possible on most PHP 5.2 installs and still actively developed) way to detect a files MIME type in PHP.我正在寻找最好的方法(可能在大多数 PHP 5.2 安装并且仍在积极开发中)来检测 PHP 中的文件 MIME 类型。

I'm aware of the mime_content_type() method and the Fileinfo extension, however mime_content_type() is unreliable and deprecated, and Fileinfo doesn't come in a "standard" PHP (5.2) install.我知道mime_content_type()方法和 Fileinfo 扩展名,但是mime_content_type()不可靠且已弃用,并且 Fileinfo 不是“标准” PHP (5.2) 安装。

Do I have any other options?我还有其他选择吗?

(lol sorry I realized this was asked months ago as I was finishing up. oh well. might as well add this...) (大声笑对不起,我意识到这是几个月前我完成的时候问的。哦,好吧。不妨添加这个......)

If it's a *nix server you could use file command.如果它是 *nix 服务器,您可以使用file命令。

file -bi <filepath>

You'd have to use "exec" in PHP to do that I guess?我猜你必须在 PHP 中使用“exec”来做到这一点? I'm new to PHP so don't quote me on this but...我是 PHP 的新手,所以不要引用我的话,但是......

$content_type = exec("file -bi " . escapeshellarg($filepath));

I didn't test it so you might need to escape the path string and format the output.我没有对其进行测试,因此您可能需要转义路径字符串并格式化 output。

Dunno if this will be more reliable than the other methods.不知道这是否比其他方法更可靠。

Have you looked into this PEAR package?你看过这个 PEAR package 吗?

http://pear.php.net/package/MIME_Type http://pear.php.net/package/MIME_Type

You could do a subrequest to the webserver you are running on, then parse the header to get the mime type that way.您可以对正在运行的网络服务器执行子请求,然后解析 header 以获取 mime 类型。 Since this is slow, use curl to only get the headers not the full request.由于这很慢,因此使用 curl 仅获取标头而不是完整请求。 This is important if you are looking at large files.如果您正在查看大文件,这一点很重要。

If you are running Apache and using php as a module, take a look at the VIRTUAL function.如果您正在运行 Apache 并使用 php 作为模块,请查看 VIRTUAL function。 it is a faster way to do a subrequest than using curl.这是一种比使用 curl 更快的方法来执行子请求。

Otherwise, you can lookup the mime type by extension.否则,您可以通过扩展名查找 mime 类型。 This will make all well named files work.这将使所有命名良好的文件都能正常工作。

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

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