dfridrich / php-mime-type
一个简单的PHP类,用于根据文件扩展名猜测文件MIME类型,并能够在Symfony项目中使用。
v3.0.1
2023-12-09 10:29 UTC
Requires
- php: ^8.1
Requires (Dev)
- phpunit/phpunit: ^10
- symfony/http-foundation: ^4.4|^5.0|^6.0|^7.0
Suggests
- symfony/http-foundation: Allows you to get prepared Symfony response.
This package is auto-updated.
Last update: 2024-09-09 13:01:17 UTC
README
一个简单的PHP类,用于根据文件扩展名猜测文件MIME类型,并能够在Symfony项目中使用。
安装
composer require dfridrich/php-mime-type
用法
基本用法
<?php // from string, can be used on non-existing files echo \Defr\PhpMimeType\MimeType::get('index.php'); // outputs text/html // from SplFileInfo echo \Defr\PhpMimeType\MimeType::get(new \SplFileInfo('Video.avi')); // outputs application/octet-stream // from SplFileObject echo \Defr\PhpMimeType\MimeType::get(new \SplFileObject('Image.JPEG')); // outputs image/jpeg // from string echo \Defr\PhpMimeType\MimeType::get('someStrange.extension'); // outputs application/octet-stream // Multiple files $files = ['index.php', new \SplFileInfo('Video.avi'), new \SplFileObject('example.php')]; /** @var \Defr\PhpMimeType\MimeTypeInfo[] $mimeTypes */ $mimeTypes = \Defr\PhpMimeType\MimeType::multiple($files); foreach ($mimeTypes as $mimeType) { echo sprintf('File "%s" is mime type "%s"', $mimeType->getFileName(), $mimeType->getMimeType()).'<br>'; } // Guess FontAwesome icon echo \Defr\PhpMimeType\MimeType::getFontAwesomeIcon('test.pdf'); // fa fa-file-pdf-o // ...with fixed width icon echo \Defr\PhpMimeType\MimeType::getFontAwesomeIcon('test.pdf', true); // fa fa-file-pdf-o fa-fw
Symfony响应
如果您想使用Symfony响应功能,也需要安装HTTP Foundation包。
composer require symfony/http-foundation
只需传递文件名或SPL对象给响应方法,您将得到一个Symfony\Component\HttpFoundation\Response对象。默认情况下,处置方式为附件,您可以更改为内联或使用Symfony ResponseHeaderBag的常量DISPOSITION_ATTACHMENT或DISPOSITION_INLINE。
<?php // Return response to download this file as attachment (default) $response = \Defr\PhpMimeType\MimeType::response(__FILE__); $response->send(); // Return response to download this file inline $response = \Defr\PhpMimeType\MimeType::response(__FILE__, \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_INLINE); $response->send(); // You can use FileAsResponse object too (and own file name) $response = \Defr\PhpMimeType\FileAsResponse::get(__FILE__, null, "my-own-file-name.txt"); $response->send(); // Or directly send it to browser $response = \Defr\PhpMimeType\FileAsResponse::send(__FILE__);
更多示例和文档
请参阅更多示例。
API文档可以在这里找到。
测试
composer test
致谢
贡献者
- Dennis Fridrich
- Nick Shek
- Giso Stallenberg
- sml-joyo
感谢...
- freepik.com - 为logo提供了照片
- svogal - 这位朋友启发我创建了这个库
- colemanw - 他的gist启发我添加了FontAwesome支持
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件。