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

php获取文件mime类型的四种方法

WBOY
WBOYOriginal
2016-07-25 09:00:301158Durchsuche
php获取文件mime类型的四种方法,比如用mime_content_type()函数判断获取mime类型、Fileinfo 获取文件MIME类型(finfo_open)等,有需要的朋友,可以参考下。

何为MIME类型,它是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问时,浏览器会自动使用指定应用程序来打开。 多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。 参考链接:php文件格式(mime类型)对照表 。 1、mime_content_type()函数判断获取mime类型 mime_content_type返回指定文件的MIME类型,用法:

echo mime_content_type ( 'php.gif' ) . "\n" ;
echo mime_content_type ( 'test.php' );

输出: image/gif text/plain

但是php 5.3.0已经将该函数废弃。如果仍想使用此函数,那么可以对php进行配置启用magic_mime扩展。

2、php Fileinfo 获取文件MIME类型(finfo_open)

PHP官方推荐mime_content_type()的替代函数是Fileinfo函数。PHP 5.3.0+已经默认支持Fileinfo函数(fileinfo support-enabled),不必进行任何配置即可使用finfo_open()判断获取文件MIME类型。用法:

$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);

3、image_type_to_mime_type()获取图片MIME类型

如果需要判断MIME类型的文件只有图像文件,那么首先可以使用exif_imagetype()函数获取图像类型常量,再用image_type_to_mime_type()函数将图像类型常量转换成图片文件的MIME类型。

注意:需要在php.ini中配置打开php_mbstring.dll(Windows需要)和extension=php_exif.dll。

4、php上传文件获取MIME类型 如果使用php上传文件,检测上传文件的MIME类型,则可以使用全局变量$_FILES['uploadfile']['type'],由客户端的浏览器检测获取文件MIME类型。



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