根据文件的资源检测文件的内容类型


Detecting content type of a file based on its resource

我正在尝试根据文件的资源确定文件的内容类型。大致如下:

$resource = fopen('/path/to/file', 'r');
$contentType = getContentTypeFromResource($resource);

我知道一种方法可以根据文件的位置在 PHP 中获取文件的内容类型:

// Method 1
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($finfo, '/path/to/file');

不幸的是,由于原因太长而无法在这里详细介绍,我从资源中确定这一点会容易得多。

这可能吗?

我知道

有点晚了,但我们不能为此使用 tmpfile 吗?

像这样:

$encoded = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
$resource = base64_decode($encoded);
$tmp = tmpfile();
fwrite($tmp, $resource);
rewind($tmp);
echo mime_content_type($tmp);
fclose($tmp);

似乎至少对我有用。