kieranbarnes Independent PHP, WordPress & CubeCart Programmer

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

  1. <?php
  2. require_once 'MIME/Type.php';
  3.  
  4. $filename = '/path/to/some/file.jpg';
  5. echo MIME_Type::autoDetect($filename);
  6. ?>

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

  1. <?php
  2. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  3. foreach (glob("*") as $filename) {
  4. echo finfo_file($finfo, $filename) . "\n";
  5. }
  6. finfo_close($finfo);
  7. ?>

Related posts

  1. The Beauty of Old Code
    A client of mine needed a quick image upload feature to a custom administration app....
  2. 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...
  3. PHP Export as CSV
    A client recently requested an option to extract search results from their PHP application as...
  4. Installing memcached on CentOS/cPanel
    memcached a (distributed) memory object caching system vital if your running a HA Linux* setup...
  5. Read a file into an array
    Here's something that puddled me for a while... $filename = 'file.txt'; $file_handle = fopen($filename, 'r');...

Posted by Kieran


Tagged as: , , , Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.