Home » Php » file type – Best way to recognize a filetype in php

file type – Best way to recognize a filetype in php

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

You can use finfo_file

<?php
echo finfo_file(finfo_open(FILEINFO_MIME), "foo.png");
?>

Answer:

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.

Answer:

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);
?>

Answer:

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.