17

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?

Martin Prikryl
  • 147,050
  • 42
  • 335
  • 704
Zwen2012
  • 2,868
  • 7
  • 33
  • 56
  • Possible duplicate of [How to get the mime type of a file after using file\_get\_contents from a remote server](http://stackoverflow.com/questions/4671672/how-to-get-the-mime-type-of-a-file-after-using-file-get-contents-from-a-remote-s) – miken32 Feb 09 '17 at 01:21

3 Answers3

44

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;
Ram Sharma
  • 8,368
  • 7
  • 38
  • 53
  • 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_type – Jean-Charles LUC Jul 16 '19 at 15:45
5

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.

Florin Asăvoaie
  • 755
  • 1
  • 5
  • 19
3

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";
}
Martin Prikryl
  • 147,050
  • 42
  • 335
  • 704