سؤال

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)

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

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)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top