rosell-dk/image-mime-type-guesser

猜测图像的MIME类型

1.1.2 2024-04-06 13:55 UTC

This package is auto-updated.

Last update: 2024-09-06 16:53:28 UTC


README

Latest Stable Version Minimum PHP Version Build Status Coverage Software License Monthly Downloads Dependents

检测/猜测图像的MIME类型

你需要确定一个文件是否是图像吗?
也许你还需要知道图像的MIME类型?

– 你来到正确的库了。

好吧,实际上这个库不能提供适用于所有平台的图像MIME类型检测,但它可以尝试一系列方法,并且可以选择性地回退到根据文件扩展名猜测。

当前(按此顺序)的检测方法栈包括:

  • 此签名嗅探器 不需要任何扩展。仅识别流行图像格式
  • finfo 需要启用fileinfo扩展。(PHP 5 >= 5.3.0,PHP 7,PHP 8,PECL fileinfo >= 0.1.0)
  • exif_imagetype 需要PHP编译时启用exif(PHP 4 >= 4.3.0,PHP 5,PHP 7,PHP 8)
  • mime_content_type 需要fileinfo。(PHP 4 >= 4.3.0,PHP 5,PHP 7,PHP 8)

请注意,除了签名嗅探器之外的所有这些方法都依赖于服务器上的MIME类型映射(Apache中的mime.types文件)。如果服务器不了解某种MIME类型,则不会检测到它。但这并不意味着这些方法依赖于文件扩展名。将png文件重命名为"png.jpeg"也将被正确识别为image/png

除了检测方法之外,该库还包含一个将文件扩展名映射到MIME类型的方法。虽然它相当有限。

安装

使用composer安装

composer require rosell-dk/image-mime-type-guesser

用法

要检测文件的MIME类型,请使用ImageMimeTypeGuesser::detect($filePath)。如果文件被识别为图像,则返回MIME类型。如果不识别为图像,则返回false。如果无法确定MIME类型(例如,由于没有可用的方法),则返回null

示例

use ImageMimeTypeGuesser\ImageMimeTypeGuesser;
$result = ImageMimeTypeGuesser::detect($filePath);
if (is_null($result)) {
    // the mime type could not be determined
} elseif ($result === false) {
    // it is NOT an image (not a mime type that the server knows about anyway)
    // This happens when:
    // a) The mime type is identified as something that is not an image (ie text)
    // b) The mime type isn't identified (ie if the image type is not known by the server)
} else {
    // it is an image, and we know its mime type!
    $mimeType = $result;
}

为了方便起见,您可以使用detectIsIn方法来测试检测是否在MIME类型列表中。

if (ImageMimeTypeGuesser::detectIsIn($filePath, ['image/jpeg','image/png'])) {
    // The file is a jpeg or a png
}

detect方法不会回退到根据文件扩展名映射。在大多数情况下,您不需要这样做。在某些情况下,这样做可能不安全。例如,如果您想阻止用户上传可执行文件,您可能不希望允许用户上传具有无辜外观的文件扩展名,如"evil-exe.jpg"。

然而,在某些情况下,您可能只需要一个最佳猜测,在这种情况下,回退到从文件扩展名映射是有意义的。在这种情况下,您可以使用guess方法而不是detect方法。或者您可以使用lenientGuess。宽容猜测更加宽松,不仅会在检测返回null时回退到映射,甚至在检测返回false时也会回退到映射。

警告:当您的目标是保护服务器免受有害上传时,从文件扩展名猜测是不适合的。

注意:只有有限的一组图像扩展名被扩展名到MIME类型映射器所识别,具体如下:{apng, avif, bmp, gif, ico, jpg, jpeg, png, tif, tiff, webp, svg}。如果您需要其他特定类型,请随意提交PR,或者创建一个issue请求我完成。

示例

$result = ImageMimeTypeGuesser::guess($filePath);
if ($result !== false) {
    // It appears to be an image
    // BEWARE: This is only a guess, as we resort to mapping from file extension,
    //         when the file cannot be properly detected.
    // DO NOT USE THIS GUESS FOR PROTECTING YOUR SERVER
    $mimeType = $result;
} else {
    // It does not appear to be an image
}

猜测函数也提供了一些便利方法来测试一系列MIME类型。它们分别被称为 ImageMimeTypeGuesser::guessIsInImageMimeTypeGuesser::lenientGuessIsIn

示例

if (ImageMimeTypeGuesser::guessIsIn($filePath, ['image/jpeg','image/png'])) {
    // The file appears to be a jpeg or a png
}

替代方案

其他嗅探器

你喜欢我的工作吗?

也许你想支持我的工作,这样我就可以继续做下去:)