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
$finfo = finfo_open(FILEINFO_MIME_TYPE);
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>Related posts:
- PHP Export as CSV
A client recently requested an option to extract search results from their PHP application as... - iCalendar Generation
One of my clients requested that the CRM applicationI wrote should interact with Outlook Calender.... - The Beauty of Old Code
A client of mine needed a quick image upload feature to a custom administration app.... - CAPTCHA Image Generation
I couldn't find a very good CAPTCHA generation script in PHP, all the ones I... - Read a file into an array
Here's something that puddled me for a while... $filename = 'file.txt'; $file_handle = fopen($filename,...