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

4

24

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?

Perusse answered 11/8, 2014 at 6:35 Comment(1)
F
57

Yes, you can get it like this.

$image_url = "mydomain.com/myimage.jpg";
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($image_url));
echo $mime_type;
Funke answered 11/8, 2014 at 6:40 Comment(1)
be careful using $file->buffer it can use a lot of memory. For a 18 MB file, PHP peaked at 220 MB (it was at 50MB before calling ->buffer)! I had to put_file_contents then mime_content_typeBriar
D
11

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");
$headers = implode("\n", $http_response_header);
if (preg_match_all("/^content-type\s*:\s*(.*)$/mi", $headers, $matches)) {
    $content_type = end($matches[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).

Dressage answered 1/3, 2018 at 18:10 Comment(1)
Awesome job Martin!Cottrell
M
6

Be very careful what you do by checking only the Mime Type! If you really want to be sure that an image is actually an image, the safest way to do this is open it with an image manipulation library and write it with the library. This will both fail if the image is actually malicious code and guarantee that you are actually writing an image file to the disk. Just as an example for this, you can easily trick MIME into thinking that some malicious code is GIF.

To answer your questions more directly, use the FileInfo PECL module.

Major answered 11/8, 2014 at 6:49 Comment(0)
F
-1

Simplest solution:

you can get the MIME TYPE easily with the file path:

$mime_type = mime_content_type($filePath);

for anyone who comes next (like me) and does not like other solutions.

Faust answered 20/12, 2023 at 7:36 Comment(2)
That won't work if the file is not persisted anywhereVanettavang
sorry, I missed the part where he said he only has the body of the image @NicoHaaseFaust

© 2022 - 2024 — McMap. All rights reserved.