How to get the mime type of a file after using file_get_contents from a remote server

You can use the finfo::buffer() method: http://php.net/finfo_buffer.

<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($cnt) . PHP_EOL;

NOTE: You could optionally use the finfo_buffer procedural function if that suites you better than using the object-oriented methodology.


You do not have to guess (aka autodetect) the MIME type.

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/");
$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";
}