Skip to content

Validating files by mime type

Uploading file in a form is always very critical. When you give your users functionality to upload some file on your site, you open many doors hackers to your site. Hackers can upload files suiting their purpose and exploit your site code. So you must check the type of file which is going to be uploaded. We have 3 methods to do this:

  1. Splitting the file name by dot(.) to get the extension and then based on this extension, decide file type.
  2. system(“file -bi — “.escapeshellarg($filename)) : Check type of file based on extension of its name. This method utilizes shell command to process.
  3. mime_content_type($filename) : This is PHP’s default method to check mime type of a file.
  4. FILEINFO: Probably the Best, as it provides extra information about file along with file type.

From above 4 methods, first 2 are prone to hacking techniques e.g. Hacker can spoof by renaming his script file with .jpg or .png etc. “FILEINFO” and “mime_content_type” methods are most accurate as they decide the type based on file’s mime time. Based on same mime type operating system decides program, to run scripts. Following is a function to demo how to use “FILEINFO” to check extension. This extension needs “php_FILEINFO” extension installed on the server.

function file_mime_type($file, $encoding=true) {

    if (function_exists('finfo_file')) {
        $finfo = finfo_open(FILEINFO_MIME); // FILEINFO_MIME_TYPE
        $mime = finfo_file($finfo, $file);
    else if (substr(PHP_OS, 0, 3) == 'WIN') {
        $mime = mime_content_type($file);
    else {
        $file = escapeshellarg($file);
        $cmd = "file -iL $file";

        exec($cmd, $output, $r);

        if ($r == 0) {
            $mime = substr($output[0], strpos($output[0], ': ')+2);

    if (!$mime) {
        return false;

    if ($encoding) {
        return $mime;

    return substr($mime, 0, strpos($mime, '; '));

This can be also used in Object-oriented style.

function _mime_content_type($filename){
    $result =new finfo();

        return $result->file($filename, FILEINFO_MIME_TYPE);

    return false;

“mime_content_type” function is much shorter to use

function getMimeType( $filename ) {
        return mime_content_type( $filename );
Published inBlogPHP