php实现获取文件mime类型的方法

yipeiwu_com7年前PHP代码库

本文实例讲述了php获取文件mime类型的方法。分享给大家供大家参考。具体如下:

1.使用 mime_content_type 方法

string mime_content_type ( string $filename )

Returns the MIME content type for a file as determined by using information from the magic.mime file.  

<?php 
$mime_type = mime_content_type('1.jpg'); 
echo $mime_type; // image/jpeg 
?>

但此方法在 php5.3 以上就被废弃了,官方建议使用 fileinfo 方法代替。

2.使用 Fileinfo 方法 (官方推荐)

使用fileinfo需要安装php_fileinfo扩展。
如已安装可以在extension_dir目录下找到php_fileinfo.dll(windows),fileinfo.so(linux)
打开php.ini,把extension=php_fileinfo.dll前的";"去掉,然后重启apache。

<?php 
$fi = new finfo(FILEINFO_MIME_TYPE); 
$mime_type = $fi->file('1.jpg'); 
echo $mime_type; // image/jpeg 
?>

3.使用 image_type_to_mime_type 方法(只能处理图象类型)

使用exif_imagetype方法需要安装php_exif扩展,并需要安装php_mbstring扩展
如已安装可以在extension_dir目录下找到php_exif.dll(windows),exif.so(linux)
打开php.ini,把 extension=php_mbstring.dll, extension=php_exif.dll 前的","去掉,然后重启apache

<?php 
$image = exif_imagetype('1.jpg'); 
$mime_type = image_type_to_mime_type($image); 
echo $mime_type; // image/jpeg 
?>

Tips:如果使用文件名的后缀来判断,因为文件后缀是可以修改的,所以使用文件后缀来判断会不准确。

希望本文所述对大家的php程序设计有所帮助。

相关文章

php根据年月获取当月天数及日期数组的方法

本文实例讲述了php根据年月获取当月天数及日期数组的方法。分享给大家供大家参考,具体如下: function get_day( $date ) { $tem = expl...

php 强制下载文件实现代码

复制代码 代码如下:<?php $file = 'monkey.gif'; if (file_exists($file)) {     header(...

php 结果集的分页实现代码

复制代码 代码如下:<?php @mysql_connect("localhost", "root","1981427") //连接数据库服务器 or die("数据库服务器连接失...

php递归实现无限分类的方法

本文实例讲述了php递归实现无限分类的方法。分享给大家供大家参考。具体如下: <?php $rows = array( array( 'id' =>...

php数组冒泡排序算法实例

本文实例讲述了php数组冒泡排序算法。分享给大家供大家参考,具体如下: <?php /*@冒泡排序算法 */ $array=array(5,45,22,11,32,28...