tags:

views:

833

answers:

4

What's the best way to discover a file's filetype within php? I heard that the browser may be tricked, so what's a better way of doing this?

+3  A: 

i think you mean finfo_file() to discover mimetype

from php.net Example:

<?php
$finfo = finfo_open(FILEINFO_MIME); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>
Luis Melgratti
+6  A: 

You can use finfo_file

<?php
echo finfo_file(finfo_open(FILEINFO_MIME), "foo.png");
?>
kajyr
Note that this method has it's own problems (ie. returning empty or ambiguous strings).
Jonathan Sampson
+2  A: 

Look at "magic numbers." The first few bytes of files usually identify what type of file it is. For example, the firts few bytes of a GIF are either 47 49 46 38 37 61 or 47 49 46 38 39 61, ASCII for GIF89a or GIF87a. There are many other "magic numbers." See http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files

EDIT: I believe this is more reliable than MIME functions on PHP.

stalepretzel
+2  A: 

You can't trust in Content-Type returned by Browser. It's based on file extension and can be easily tricked.

As stalepretzel mentioned it, best way to guess file content-type is using magic numbers. If your server is running on a *nix machine, you can use this function:

<?php

function get_file_type($file) {
  if(function_exists('shell_exec') === TRUE) {
    $dump = shell_exec(sprintf('file -bi %s', $file));
    $info = explode(';', $dump);
    return $info[0];
  }
  return FALSE;
}

?>

Usage: $file_type = get_file_type('my_file_name.ext');

PD: check /usr/share/magic.mime to more information.

Héctor Vergara R.