简体   繁体   English

如何在 PHP 中使用 file_get_contents 获取图像的 MIME 类型

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

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 .我需要获取图像的 MIME 类型,但我只有使用file_get_contents获得的图像主体。 Is there a possibility to get the MIME type?是否有可能获得 MIME 类型?

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!通过只检查 Mime 类型来非常小心你所做的! 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.举个例子,您可以轻松地诱使 MIME 认为某些恶意代码是 GIF。

To answer your questions more directly, use the FileInfo PECL module .要更直接地回答您的问题,请使用FileInfo PECL 模块

If you download a file using HTTP, do not guess (aka autodetect) the MIME type.如果您使用 HTTP 下载文件,请不要猜测(也称为自动检测)MIME 类型。 Even if you downloaded the file using file_get_contents , you can still access HTTP headers.即使您使用file_get_contents下载了文件,您仍然可以访问 HTTP 标头。

Use $http_response_header to retrieve headers of the last file_get_contents call (or any call with http[s]:// wrapper ).使用$http_response_header检索最后一次file_get_contents调用(或任何带有http[s]:// 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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM