I need to get the MIME type of an image, but I only have the body of the image which I\'ve got with file_get_contents
. Is there a possibility to get the MIME type?<
If you download a file using HTTP, do not guess (aka autodetect) the MIME type. Even if you downloaded the file using file_get_contents
, you can still access HTTP headers.
Use $http_response_header to retrieve headers of the last file_get_contents
call (or any call with http:// wrapper).
$contents = file_get_contents("https://www.example.com/image.jpg");
$pattern = "/^content-type\s*:\s*(.*)$/i";
if (($header = array_values(preg_grep($pattern, $http_response_header))) &&
(preg_match($pattern, $header[0], $match) !== false))
{
$content_type = $match[1];
echo "Content-Type is '$content_type'\n";
}