Created
March 15, 2016 22:13
-
-
Save webmechanicx/b54c7d5445f74c773837 to your computer and use it in GitHub Desktop.
Get the Mine-Type of a File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* get mime data of the file. | |
* @return {String} mime-type of the given file | |
* @param $filename String | |
*/ | |
function get_mime($filename){ | |
preg_match("/\.(.*?)$/", $filename, $m); # Get File extension for a better match | |
switch(strtolower($m[1])){ | |
case "js": return "application/javascript"; | |
case "json": return "application/json"; | |
case "jpg": case "jpeg": case "jpe": return "image/jpg"; | |
case "png": case "gif": case "bmp": return "image/".strtolower($m[1]); | |
case "css": return "text/css"; | |
case "xml": return "application/xml"; | |
case "html": case "htm": case "php": return "text/html"; | |
default: | |
if(function_exists("mime_content_type")){ # if mime_content_type exists use it. | |
$m = mime_content_type($filename); | |
}else if(function_exists("")){ # if Pecl installed use it | |
$finfo = finfo_open(FILEINFO_MIME); | |
$m = finfo_file($finfo, $filename); | |
finfo_close($finfo); | |
}else{ # if nothing left try shell | |
if(strstr($_SERVER[HTTP_USER_AGENT], "Windows")){ # Nothing to do on windows | |
return ""; # Blank mime display most files correctly especially images. | |
} | |
if(strstr($_SERVER[HTTP_USER_AGENT], "Macintosh")){ # Correct output on macs | |
$m = trim(exec('file -b --mime '.escapeshellarg($filename))); | |
}else{ # Regular unix systems | |
$m = trim(exec('file -bi '.escapeshellarg($filename))); | |
} | |
} | |
$m = split(";", $m); | |
return trim($m[0]); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment