2

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)

siliconpi
  • 8,105
  • 18
  • 69
  • 107
  • Need more context ... the tag 'file-upload' implies you're dealing with uploaded files, in which case the file type should be in the request? – chrisdowney Jun 16 '11 at 10:40

3 Answers3

3

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.

mario
  • 144,265
  • 20
  • 237
  • 291
2

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

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)

Lepidosteus
  • 11,779
  • 4
  • 39
  • 51