I am trying to determine a file's mime type. I've tried a few methods, but haven't come up with anything that gives consistent output. I've tried $mime = mime_content_type($file)
and $mime = exec('file -bi ' . $file)
. I am serving up images, CSS, and JavaScript.
Example mime_content_type()
output:
- jquery.min.js - text/plain
- editor.js - text/plain
- admin.css - text/plain
- controls.css - application/x-troff
- logo.png - text/plain
Example exec(...)
output:
- jquery.min.js - text/plain; charset=us-ascii
- editor.js - text/x-c++; charset=us-ascii
- admin.css - text/x-c; charset=us-ascii
- controls.css - text/x-c; charset=us-ascii
- logo.png - image/png
As can be seen here, the results are all over the place.
My PHP version is 5.2.6
SOLUTION (thanks to Jacob)
$mimetypes = array(
'gif' => 'image/gif',
'png' => 'image/png',
'jpg' => 'image/jpg',
'css' => 'text/css',
'js' => 'text/javascript',
);
$path_parts = pathinfo($file);
if (array_key_exists($path_parts['extension'], $mimetypes)) {
$mime = $mimetypes[$path_parts['extension']];
} else {
$mime = 'application/octet-stream';
}