Skip to content
Advertisement

How do I find the MIME type of a file with PHP?

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

<?php
   include('/www/site'.$_SERVER['REQUEST_URI']);
?>

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?

Advertisement

Answer

If you are sure you’re only ever working with images, you can check out the 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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement