Skip to content

Instantly share code, notes, and snippets.

@humbletiger
Last active July 27, 2020 02:23
Show Gist options
  • Save humbletiger/d3e1a70602d6d53e613ac90995b07b12 to your computer and use it in GitHub Desktop.
Save humbletiger/d3e1a70602d6d53e613ac90995b07b12 to your computer and use it in GitHub Desktop.
Function to set precedence to Apache mime types repo (with PHP mime_content_type fallback). Caches repo locally to avoid unnecessary http calls.
<?php
/**
ABSTRACT
Sets precedence to Apache mime types repo at http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
Caches the Apache repo locally (in php temp folder) to avoid unnecessary http calls.
Fallback to native PHP mime_content_type function if no extension match.
USAGE
mime_types('/var/www/html/index.php'); // response: text/x-php
mime_types('js'); // response: application/javascript
mime_types(); // returns a full Apache repo array (from cached repo if possible).
e.g.:
Array
(
[3dml] => text/vnd.in3d.3dml
[3ds] => image/x-3ds
[3g2] => video/3gpp2
[3gp] => video/3gpp
[7z] => application/x-7z-compressed
[aab] => application/x-authorware-bin
...
mime_types(true); // refreshes cached repo from Apache source and returns full array.
*/
function mime_types($data='') {
$url = 'http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types';
$local = sys_get_temp_dir().'/mime.types';
if ( $data === true ) {
@unlink($local); // Clear cache
$data='';
}
// Define extension from name or file path.
$extension=false;
if ( !empty($data) ) {
if ( strstr($data,'.') ) {
$extension=pathinfo(basename($data),PATHINFO_EXTENSION);
}else{
$extension=$data;
}
}
// Use locally cached array if exists.
if ( realpath($local) ) {
//echo('is local');
$contents=file_get_contents(realpath($local));
$mime_types = unserialize($contents);
} else {
// Parse Apache doc to array.
$mimes = array();
foreach(@explode("\n",@file_get_contents($url)) as $x){
if(isset($x[0]) && $x[0]!=='#' && preg_match_all('#([^\s]+)#', $x, $out) && isset($out[1]) && ($c = count($out[1])) > 1){
for($i=1; $i < $c; $i++){
$mimes[$out[1][$i]] = $out[1][0];
}
}
}
$mime_types = (@ksort($mimes)) ? $mimes : false;
if ( strstr($mime_types['pdf'],'application') ) {
@file_put_contents($local,serialize($mime_types));
}
}
if ( $extension ) {
if ( isset($mime_types[$extension]) ) {
return $mime_types[$extension];
}
if ( realpath($data) && function_exists('mime_content_type') ) {
return mime_content_type(realpath($data));
}
return "application/octet-stream"; // Default
}
// Return full array if no arguments.
if ( strstr($mime_types['pdf'],'application') ) {
return $mime_types;
}
return false; // Something when terribly wrong.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment