开发者

Using /usr/bin/file to determine file type?

I'm planning to use this system program /usr/bin开发者_运维问答/file to determine uploaded file content type and then act accordingly.

Is this a good idea or are there things I should watch out for? (Or use something altogether different)


mime_content_type and finfo_file are the preferred methods for determining a mime type (either one is often enabled in most php distributions). They use the same magic.mime database as the external tool, which is why I would use that as fallback only.

Using the external tool also requires extracting the mime type from the output, so it's somewhat involving code:

$type = exec("/usr/bin/file -iL " .escapeshellcmd($fn). " 2>/dev/null");
if ($type = trim(strtok(substr(strrchr($type, ":"), 1), ";"))) {
    return $type;
}

If your question is about reliability: yes, that's a good approach. Determining the file type by magic bytes is quite reliable on all current Linux/U*ix servers.


PHP has the fileinfo extension, which uses the same mechanism but is native to PHP.


If you can use a PECL extension (or are using php >= 5.3), I would recommend that you use the Fileinfo extension.

If not, the mime_content_type() function will do, but please note that it is now deprecated (in favor or fileinfo)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜