Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MIME-type of an image with file_get_contents in PHP

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?

like image 840
Zwen2012 Avatar asked Aug 11 '14 06:08

Zwen2012


People also ask

How can I get MIME type from uploaded file in PHP?

The mime_content_type() function is an inbuilt function in PHP which is used to get the MIME content-type of a file. Parameters: This function accepts single parameter $file which specifies the path of the file which MIME details to be find. Return Value: This function returns the MIME content type or False on failure.

What will the file_get_contents () return?

The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .


2 Answers

Yes, you can get it like this.

$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($image_url));
echo $mime_type;
like image 56
Ram Sharma Avatar answered Sep 18 '22 14:09

Ram Sharma


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[s]:// 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";
}

Resort to the autodetections only if the server fails to provide the Content-Type (or provides only a generic catch-all type, like application/octet-stream).

like image 28
Martin Prikryl Avatar answered Sep 20 '22 14:09

Martin Prikryl