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
<?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?
If you run Linux and have the extension you could simply read the MIME type from /etc/mime.types by making a hash array. You can then store that in memory and simply call the MIME by array key :)
If you are working with Images only and you need mime type (e.g. for headers), then this is the fastest and most direct answer:
It will output true image mime type even if you rename your image file
mime_content_type()
appears to be the way to go, notwithstanding the above comments saying it is deprecated. It is not -- or at least this incarnation ofmime_content_type()
is not deprecated, according to http://php.net/manual/en/function.mime-content-type.php. It is part of the FileInfo extension, but the PHP documentation now tells us it is enabled by default as of PHP 5.3.0.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.
if you're only dealing with images you can use the
[getimagesize()][1]
function which contains all sorts of info about the image, including the type.A more general approach would be to use the FileInfo extension from PECL. The PHP documentation for this extension can be found at: http://us.php.net/manual/en/ref.fileinfo.php
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()
For me, nothing of this does work -
mime_content_type
is deprecated,finfo
is not installed, andshell_exec
is not allowed.