While you can somewhat rely on the name extension of a file to determine the mime type, it may not always be accurate. For example, .jpg and .jpeg files are very probably image/jpeg files and .png files are very probably image/png files, but there’s always an exception because file extensions can be faked. To accurately find the mime type of a specific file in PHP, you should use the Fileinfo extension.
Find out if the extension is enabled with the code outlined in the beginning part of the resize image in PHP post.
With the php_fileinfo extension enabled in php.ini, this is the function I come up with:
$finfo = new finfo(FILEINFO_MIME); // return mime type
if ($finfo) {
$file_name = "/absolute/path/to/some.jpg"; /* Must use absolute path */
$file_info = $finfo->file($file_name);
$mime_type = substr($file_info, 0, strpos($file_info, ';'));
echo $mime_type;
}
Which will get you this:
image/jpeg
The reason it gets complicated in the echo line is that the standard output of FILEINFO_MIME information output by the file() function of the $finfo object is something like this:
image/jpeg; charset=binary
Therefore, you have to literally get everything before the semi-colon to get the mime type information.
If it was a CSS file, the output of the $finfo->file() method would be like this:
text/plain; charset=utf-8
Cool, huh!