Does PHP have a function that returns a file extension given a content type?
I’m looking for something that works like:
<?php
function getFileExtension($contentType)
{
if ($contentType === 'image/png')
{
return '.png';
}
elseif ($contentType === 'image/jpg')
{
return '.jpg';
}
elseif ($contentType === 'application/zip')
{
return '.zip';
}
else
{
return FALSE;
}
}
The goal is to use a library function that has all content types handled. Based on the pattern above, I guess I could roll my own with something like this:
<?php
function getFileExtension($contentType)
{
$pieces = explode('/', $contentType);
return '.' . array_pop($pieces);
}
… but that seems janky. Anybody know of an already authored PHP solution? LMK. Thanks!
Given the limited number of file types stored within my application’s database, the following class/method was an acceptable solution.
Before settling on the above solution though, I did some searching on Google (as suggested by @whichdan) and found the following “extension to MIME type” mapping resource.
http://www.webmaster-toolkit.com/mime-types.shtml
After doing some analysis on the data presented in the above URL it became clear that there isn’t a definitive solution for this problem (which is probably why there isn’t a “content type to file extension” function in PHP).
To illustrate this fact for the benefit of the Stack Overflow community, I parsed the data presented in the above URL and split each content type into one of two categories – either “DEFINITIVE” OR “AMBIGUOUS”. Running var_export on each of my “post parse” arrays results in the following PHP code.
…and…