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?
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:
I actually got fed up by the lack of standard MIME sniffing methods in PHP. Install fileinfo... Use deprecated functions... Oh these work, but only for images! I got fed up of it, so I did some research and found the WHATWG Mimesniffing spec - I believe this is still a draft spec though.
Anyway, using this specification, I was able to implement a mimesniffer in PHP. Performance is not an issue. In fact on my humble machine, I was able to open and sniff thousands of files before PHP timed out.
Here is the MimeReader class.
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''
which doesnt use finfo, exec or deprecated function
works well also with remote ressources!
You can use finfo to accomplish this as of PHP 5.3:
The FILEINFO_MIME_TYPE flag is optional; without it you get a more verbose string for some files; (apparently some image types will return size and colour depth information). Using the FILEINFO_MIME flag returns the mime-type and encoding if available (e.g. image/png; charset=binary or text/x-php; charset=us-ascii). See this site for more info.
The mime of any file on your server can be gotten with this
I haven't used it, but there's a PECL extension for getting a file's mimetype. The official documentation for it is in the manual.
Depending on your purposes, a file extension can be ok, but it's not incredibly reliable since it's so easily changed.