intervention / mimesniffer
PHP MIME 类型嗅探器
2.0.0
2024-05-04 10:11 UTC
Requires
- php: ^8.1
Requires (Dev)
- phpstan/phpstan: ^1
- phpunit/phpunit: ^10.0
- slevomat/coding-standard: ~8.0
- squizlabs/php_codesniffer: ^3.8
README
在 PHP 中检测 MIME 内容类型非常简单,可以使用 mime_content_type 或 Fileinfo。但 Fileinfo 作为扩展有时在服务器上不可用。函数 mime_content_type
需要一个文件系统路径作为参数,并且如果只有字符串值则不会处理。这个包使得检测给定文件或字符串的内容的 MIME 类型变得非常简单,无需任何扩展依赖。
安装
通过 composer 轻松安装包
composer require intervention/mimesniffer
使用方法
以下是一些代码示例,展示如何处理这个库。
use Intervention\MimeSniffer\MimeSniffer; use Intervention\MimeSniffer\Types\ImageJpeg; // universal factory method $sniffer = MimeSniffer::create($content); // or detect given string $sniffer = MimeSniffer::createFromString($content); // or detect given file $sniffer = MimeSniffer::createFromFilename('image.jpg'); // or detect from file pointer $sniffer = MimeSniffer::createFromFilename(fopen('test.jpg', 'r')); // returns object of detected type $type = $sniffer->getType(); $bool = $type->isBinary(); // check if we have binary data $bool = $type->isImage(); // check if we are dealing with an image $bool = $type->isVideo(); // check video data was detected $bool = $type->isAudio(); // check if we have detected audio data $bool = $type->isArchive(); // check if an archive was detected $type = (string) $type; // cast type to string (e.g. "image/jpeg") // you can also check, if the content matches a specific type $bool = $sniffer->matches(new ImageJpeg); // or check, if the content matches an array of types $bool = $sniffer->matches([ImageJpeg::class, ImageGif::class]); // or check, if the content matches an array of type objects $bool = $sniffer->matches([new ImageJpeg, $type]);
如果您喜欢非静态初始化
use Intervention\MimeSniffer\MimeSniffer; // create instance with constructor $sniffer = new MimeSniffer($content); // with setter for given content $type = $sniffer->setFromString($other_content)->getType(); // or with setter for filename $type = $sniffer->setFromFilename('images/image.jpg')->getType(); // or with setter for file pointer $type = $sniffer->setFromPointer(fopen('images/image.jpg', 'r'))->getType();
目前只能检测以下文件类型。在下一个版本中将会添加更多。
图像
- JPEG 原始编码或 JFIF 或 Exif 文件格式的图像
- 使用 Graphics Interchange Format (GIF) 编码的图像文件
- 使用 Portable Network Graphics 格式 (PNG) 编码的图像
- BMP 文件编码的图像,一种位图格式
- High Efficiency Image File Format (HEIC/HEIF) 编码的图像
- ICO 文件格式的图标编码
- Google WebP 图像格式的图像
- 可伸缩矢量图形 (SVG)
- 标签图像文件格式 (TIFF)
- Adobe Photoshop 文档文件格式 (PSD) 编码的图像
- AV1 图像文件格式 (AVIF)
归档
- GZIP 压缩
- ZIP 文件
- RAR 归档
- TAR 文件
视频
- AVI
- MPEG-1 和 MPEG-2 视频
- MKV 媒体容器
音频
- MP3 文件
- FLAC 文件
其他
- PDF 文档
- OGG 媒体容器
- SQLite 数据库
- application/octet-stream(默认二进制)
- text/plain(默认)
贡献
欢迎贡献。在提交拉取请求之前,请注意以下指南。
- 遵循 PSR-2 编码标准。
- 为新的函数和添加的功能编写测试
开发与测试
这个包附带一个 Docker 镜像,用于构建测试套件和分析容器。要在您的系统上构建此容器,您必须安装 Docker。您可以使用以下命令运行所有测试。
docker-compose run --rm --build tests
在代码库上运行静态分析器。
docker-compose run --rm --build analysis
作者
这个库是由 Oliver Vogel 开发和维护的。
许可证
Intervention MimeSniffer 在 MIT 许可证 下授权。