[Warning to the casual reader…this post is filed under Monkey Brains, with all that that entails.]
Today during the course of my work I whipped up this quick, easy php function for getting the mime-type of a file based on the extension of the file name. I’m sure there are many different and/or better ways of doing this, but I thought my way was kind of…cute. Also, for the purposes of what I was trying to do, it only made sense to include mime-types that you’d generally come across when dealing with webpages.
function getMimeTypeFromExtension($file_name) { $file_extension = preg_replace('/.*\.([^$]*)$/', '$1', $file_name); $mime_type_array = array( 'bmp' => 'image/bmp', 'doc' => 'application/msword', 'gif' => 'image/gif', 'htm' => 'text/html', 'html' => 'text/html', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'pdf' => 'application/pdf', 'png' => 'image/png', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'txt' => 'text/plain', 'xls' => 'application/vnd.ms-excel' ); $mime_type = $mime_type_array[$file_extension]; if ($mime_type == '') { $mime_type = NULL; } return $mime_type; }
As a personal style note, I always use double-quotes and not single-quotes in code because I think it generally makes the code more portable. I did a find and replace here because WordPress wants to escape double-quotes inside <pre>
tags with backslashes. Keep an eye out for a future post in which I maniacally rant about the uniformity of formatting standards in code.
Also, a week or so ago I wrote a simple javascript form for testing regular expression replacements. I put it up here for public consumption. I love RegEx. It is really a shame that regular expressions are not supported in ActionScript , although there are a couple decent custom RegEx objects out there:
http://www.jurjans.lv/flash/RegExp.html
http://homepage.ntlworld.com/andy_black/andy/flash/regexp/
One Response to Simple Pleasures