This post is archived and probably outdated.

A hidden gem in PHP 5.3: fileinfo

2008-12-17 00:58:00

PHP 5.3.0 Alpha 3 has recently been released and marks the feature-complete set of stuff the upcoming release will offer. There was lots of talk about namespaces so other stuff could easily get lost in the long NEWS file so I plan to present some of the more hidden gems, sometimes just a new function, sometimes new language constructs. This series is not meant to be complete but some personal choice, these blog postings are also no replacement for documentation, but just pointers. My goal is that you try out 5.3 right now so we can fix bugs as soon as possible before releasing it :-)

The NEWS file has a quite short entry for my first subject:

Added fileinfo extension as replacement for mime_magic extension. (Derick)

So what's fileinfo? - Fileinfo is a solution for a quite common problem: Consider you offer downloads and want to set the correct Content-Type HTTP header. How do you get the mime type to use? Many applications go by the file extension, keep a list of them and then set the header accordingly. Problem there: You have jsut a very limited set of extensions in your list and so chances are high your file isn't there. Other workarounds include calling "file" using exec() or mime_content_type() which has been deprecated for ages.

So why is it better than the old mime_content_type()? The biggest benefit is simpler configuration, for using the old function you had to configure a magic file somewhere, fileinfo includes that file so there's no need for special configuration. Additionally fileinfo can not only work on files in the filesystem but, for instance, also on strings in memory. So if you have your data in memory finfo_buffer() will tell you the mime type of some variable content or you can use PHP stream wrappers.

For people with legacy code there's a nice change included: mime_content_type() is now using fileinfo, too, internally so people using it benefit from the improvements in fileinfo without any trouble. For getting started: Take a look at the fine manual which includes examples to get you started.