首页 php

PHP 获取文件的MimeType

发布于: 2021-02-04

本地路径获取

mime_content_type

如果你的PHP版本是< 5.3 的,可以直接使用

1
echo mime_content_type("a.jpg");

该方法在PHP 5.3就废弃了,如果仍想使用此函数,那么可以对php进行配置启用magic_mime扩展。

Fileinfo函数

PHP 5.3及以上版本,官方推荐使用Fileinfo函数来获取mime-type,需要开启file_info扩展。

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

image_type_to_mime_type():

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

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

远程链接获取

get_headers():

1
2
3
$strUrl = "http://domian.com/demo.png";
$arrTmp = get_headers($strUrl,true);
$mime_type = $arrTmp['Content-Type'];

CURL

1
2
3
4
5
6
7
8
9
10
$strUrl = "http://domian.com/demo.png";
$ch = curl_init($strUrl);
curl_setopt($ch,CURLOPT_HEADER,1);
curl_setopt($ch,CURLOPT_NOBODY,1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$tmp = curl_exec($ch);
//$mime_type = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);
curl_close($ch);
preg_match('/Content-Type:\s(.*)\s/',$tmp,$arr);
$mime_type = $arr[1];