Heim  >  Artikel  >  Backend-Entwicklung  >  php 获取文件mime类型的方法

php 获取文件mime类型的方法

WBOY
WBOYOriginal
2016-08-08 09:32:06841Durchsuche

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(&#39;1.jpg&#39;);
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(&#39;1.jpg&#39;);
$mime_type = image_type_to_mime_type($image);
echo $mime_type; // image/jpeg
?>

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

以上就介绍了php 获取文件mime类型的方法,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn