How to get MIME type of image with get_contents file in PHP

I need to get the MIME type of the image, but I only have the body of the image, which I have with file_get_contents . Is it possible to get a MIME type?

+13
content-type mime-types php file-get-contents
source share
3 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; 
+29
source share

Be very careful when checking only Mime Type! If you really want to be sure that the image is actually an image, the safest way to do this is to open it using the image manipulation library and write it along with the library. This will fail if the image is actually malicious code and ensures that you are actually writing the image file to disk. For example, you can easily fool MIME into thinking that some kind of malicious code is a GIF.

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

+5
source share

If you upload a file using HTTP, do not guess (also called auto-detection) the MIME type. Even if you uploaded the file using file_get_contents , you can still access the HTTP headers.

Use $http_response_header to get the headers of the last call to file_get_contents (or any call from http:// wrapper ).

 $contents = file_get_contents("https://www.example.com/image.jpg"); $pattern = "/^content-type\s*:\s*(.*)$/i"; if (($header = preg_grep($pattern, $http_response_header)) && (preg_match($pattern, array_shift(array_values($header)), $match) !== false)) { $content_type = $match[1]; echo "Content-Type is '$content_type'\n"; } 
0
source share

All Articles