Breadcrumbs

PHP: Determining MIME Type

PHP lacks a definite way to detect the MIME type of a file across each PHP version. Older versions of PHP use the mime_content_type() (external link) function, whereas more recent versions encourage the use of the Fileinfo (external link) set of functions. These variations present a difficulty when developing an application that must work across multiple versions and installations of PHP. In order to solve this problem, I use the following code to create a function to check the MIME type of a file regardless of the development environment:

Code: PHP

<?php
// Setup replacement functions for the deprecated mime_content_type()
if (!function_exists('mime_content_type'))
{
    
// If Fileinfo extension is installed
    
if (function_exists('finfo_file'))
    {
        
/**
         * Determine a file's MIME type
         *
         * @param string $file File path
         * @return string
         */
        
function mime_content_type($file)
        {
            
$finfo finfo_open(FILEINFO_MIME);
            
$mimetype finfo_file($finfo$file);
            
finfo_close($finfo);
            
            return 
$mimetype;
        }
    }
    
// Otherwise use this method, which will not work on Windows
    
else
    {
        
/**
         * Determine a file's MIME type
         *
         * @param string $file File path
         * @return string
         */
        
function mime_content_type($file)
        {
            return 
trim(exec('file -bi '.escapeshellarg($file)));
        }
    }
}
?>

Now, with this code placed in some universally-included file, you can determine the MIME type just by using mime_content_type(some_file). The above code handles determining which way to determine the MIME type based on the current installation of PHP under which it is being run.

Sometimes, Fileinfo will not be installed on the server, in which case you can use a shell command to determine the MIME type as well. The only dilemma this code does not solve is a Windows installation of PHP without mime_content_type() and Fileinfo support. However, considering most servers running PHP are also running Linux (not Windows), this seems like an unlikely occurrence.

Tags: