Alex Rivera | Logout

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

Asked 2008-09-25T17:51:52.247
49

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?

Edit
Report

2 Answers

0

If you're only dealing with images, you can use the [getimagesize()][1] function which contains all sorts of information about the image, including the type.

A more general approach would be to use the FileInfo extension from PECL.

Some people have serious complaints about that extension... so if you run into serious issues or cannot install the extension for some reason you might want to check out the deprecated function mime_content_type().

answered 2008-09-25T18:03:18.350
-1

I got very good results using a user function from http://php.net/manual/de/function.mime-content-type.php @''john dot howard at prismmg dot com 26-Oct-2009 03:43''

function get_mime_type($filename, $mimePath = '../etc') { ...

which doesn’t use finfo, exec or a deprecated function.

It works well also with remote resources!

answered 2012-09-12T11:46:16.910

Your Answer