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

本小妞迷上赌 提交于 2019-12-03 02:01:34

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;

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.

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 = 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";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!