Detecting MIME types in PHP
Posted on January 22, 2010
Detecting MIME types in PHP used to be hellish.
Use the mime_content_type function I hear you say. Returns the MIME content type for a file as determined by using information from the magic.mime file. No, its garbage and thankfully now depreciated.
The PHP documentation suggests we use the Fileinfo PECL extension. I wasted ten minutes of my day trying to make that work. It even comes packaged with PHP 5.3. Still doesn't work. PEAR to the rescue. Again.
pear install MIME_Type
Here's how I detect a MIME Type
- <?php
- require_once 'MIME/Type.php';
-
- $filename = '/path/to/some/file.jpg';
- echo MIME_Type::autoDetect($filename);
- ?>
You can even do clevererer things like;
- getMedia() returns the main part (media part, portion before the slash) of a MIME type. It would return image for image/png.
- getSubType() returns the subtype of the given type. For image/png, it returns png.
So, until PHP sorts itself out by making the built in PECL code work, first time, trust PEAR.
Here's the none working PECL based code for reference
- <?php
- }
- ?>
Related posts
- The Beauty of Old Code
A client of mine needed a quick image upload feature to a custom administration app.... - Using WP-Ecommerce Product Downloads without checking out
I've used WP-Ecommerce for a few clients who required an online catalogue, rather than an... - PHP Export as CSV
A client recently requested an option to extract search results from their PHP application as... - Installing memcached on CentOS/cPanel
memcached a (distributed) memory object caching system vital if your running a HA Linux* setup... - Read a file into an array
Here's something that puddled me for a while... $filename = 'file.txt'; $file_handle = fopen($filename, 'r');...



