7

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?

LuRsT
  • 3,973
  • 9
  • 39
  • 51

4 Answers4

14

You can use finfo_file

<?php
echo finfo_file(finfo_open(FILEINFO_MIME), "foo.png");
?>
Carlo
  • 2,103
  • 21
  • 29
6

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
  • 15,543
  • 22
  • 76
  • 91
5

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
  • 11,881
  • 3
  • 30
  • 32
3

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
  • 173
  • 1
  • 4