How do I find the mime-type of a file with php?


Ok, so I have an index.php file which has to process many different file types. how do I guess the filetype based on the REQUEST_URI.

If I request http://site/image.jpg, and all requests redirect through index.php, which looks like this


How would I make that work correctly?

Should I test based on the extension of the file requested, or is there a way to get the filetype?

12/7/2012 10:21:17 AM

Accepted Answer

If you are sure you're only ever working with images, you can check out the getimagesize() exif_imagetype() PHP function, which attempts to return the image mime-type.

If you don't mind external dependencies, you can also check out the excellent getID3 library which can determine the mime-type of many different file types.

Lastly, you can check out the mime_content_type() function - but it has been deprecated for the Fileinfo PECL extension.

2/26/2014 4:46:14 AM

mime_content_type() is deprecated, so you won't be able to count on it working in the future. There is a "fileinfo" PECL extension, but I haven't heard good things about it.

If you are running on a *nix server, you can do the following, which has worked fine for me:

$file = escapeshellarg( $filename );
$mime = shell_exec("file -bi " . $file);
$filename should probably include the absolute path.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow