note 92399 deleted from function.mime-content-type by danbrown

From: Date: Tue, 27 Oct 2009 14:26:00 +0000
Subject: note 92399 deleted from function.mime-content-type by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162153@lists.php.net to get a copy of this message
Note Submitter: john dot howard at prismmg dot com ---- Here's a simple function to return MIME types, based on the Apache mime.types file. <?php function get_mime_type($filename,$mimePath = '../etc') { $fileext = substr(strrchr($filename, '.'), 1); if (empty($fileext)) return (false); $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext\s)/i"; $lines = file("$mimePath/mime.types", FILE_IGNORE_NEW_LINES); foreach($lines as $line) { if (substr($line, 0, 1) == '#') continue; // skip comments if (!preg_match($regex, $line, $matches)) continue; // no match to the extension return ($matches[1]); } return (false); // no match at all } ?> Notes: [1] Requires mime.types file distributed with Apache (normally found at ServerRoot/conf/mime.types). If you are using shared hosting, download the file with the Apache distro and then upload it to a directory on your web server that php has access to. [2] First param is the filename (required). Second parameter is path to mime.types file (optional; defaults to home/etc/). [3] Based on MIME types registered with IANA (http://www.iana.org/assignments/media-types/index.html). Recognizes 630 extensions associated with 498 MIME types. [4] Asserts MIME type based on filename extension. Does not examine the actual file; the file does not even have to exist. [5] Examples of use: >> echo get_mime_type('myFile.xml'); >> application/xml >> echo get_mime_type('myPath/myFile.js'); >> application/javascript >> echo get_mime_type('myPresentation.ppt'); >> application/vnd.ms-powerpoint >> echo get_mime_type('http://mySite.com/myPage.php); >> application/x-httpd-php >> echo get_mime_type('myPicture.jpg'); >> image/jpeg >> echo get_mime_type('myMusic.mp3'); >> audio/mpeg and so on... To create an associative array containing MIME types, use: <?php function get_mime_array($mimePath = '../etc') { $regex = "/([\w\+\-\.\/]+)\t+([\w\s]+)/i"; $lines = file("$mimePath/mime.types", FILE_IGNORE_NEW_LINES); foreach($lines as $line) { if (substr($line, 0, 1) == '#') continue; // skip comments if (!preg_match($regex, $line, $matches)) continue; // skip mime types w/o any extensions $mime = $matches[1]; $extensions = explode(" ", $matches[2]); foreach($extensions as $ext) $mimeArray[trim($ext)] = $mime; } return ($mimeArray); } ?>

« previous php.notes (#162153) next »