kieranbarnes do you know where your towel is?

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);
?>
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Related posts:

  1. PHP Export as CSV
    A client recently requested an option to extract search results from their PHP application as...
  2. iCalendar Generation
    One of my clients requested that the CRM applicationI wrote should interact with Outlook Calender....
  3. The Beauty of Old Code
    A client of mine needed a quick image upload feature to a custom administration app....
  4. CAPTCHA Image Generation
    I couldn't find a very good CAPTCHA generation script in PHP, all the ones I...
  5. Read a file into an array
    Here's something that puddled me for a while... $filename = 'file.txt'; $file_handle = fopen($filename,...

What this article useful to you?



Let me know, buy me a beer!
Alternatively, if you're feeling impecunious, you may like to subscribe to my RSS feed, or see other articles in the PHP category.

Filed under: PHP Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.