文件扩展名易伪造,且同一扩展名可能对应多种 MIME(如 .svg 既是 image/svg+xml 也可能是 text/xml)。可靠的做法是:优先检测文件魔数,次之用系统 file 命令,最后回退到扩展名映射表。
file -i/-ib:调用系统命令,需 exec 权限,适合无扩展环境。<?php
$mime = array(
// applications
'ai' => 'application/postscript', 'eps' => 'application/postscript',
'exe' => 'application/octet-stream', 'doc' => 'application/vnd.ms-word',
'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint',
'pdf' => 'application/pdf', 'xml' => 'application/xml',
'odt' => 'application/vnd.oasis.opendocument.text',
'swf' => 'application/x-shockwave-flash',
// archives
'gz' => 'application/x-gzip', 'tgz' => 'application/x-gzip',
'bz2' => 'application/x-bzip2', 'tbz' => 'application/x-bzip2',
'zip' => 'application/zip', 'rar' => 'application/x-rar',
'tar' => 'application/x-tar', '7z' => 'application/x-7z-compressed',
// texts
'txt' => 'text/plain', 'php' => 'text/x-php', 'html' => 'text/html',
'js' => 'text/javascript', 'css' => 'text/css', 'json' => 'application/json',
// images
'bmp' => 'image/x-ms-bmp', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg',
'gif' => 'image/gif', 'png' => 'image/png', 'webp' => 'image/webp',
'tiff' => 'image/tiff', 'svg' => 'image/svg+xml',
// audio
'mp3' => 'audio/mpeg', 'ogg' => 'audio/ogg', 'wav' => 'audio/wav',
'flac' => 'audio/flac', 'm4a' => 'audio/mp4',
// video
'mp4' => 'video/mp4', 'webm' => 'video/webm', 'mov' => 'video/quicktime',
'avi' => 'video/x-msvideo', 'mkv' => 'video/x-matroska',
);
function _getMimeDetect() {
if (class_exists('finfo')) return 'finfo';
if (function_exists('mime_content_type')) return 'mime_content_type';
if (function_exists('exec')) {
$r = exec('file -ib ' . escapeshellarg(__FILE__));
if (strpos($r, 'text/x-php') === 0 || strpos($r, 'text/x-c++') === 0) return 'linux';
$r = exec('file -Ib ' . escapeshellarg(__FILE__));
if (strpos($r, 'text/x-php') === 0 || strpos($r, 'text/x-c++') === 0) return 'bsd';
}
return 'internal';
}
function _getMimeType($path) {
global $mime;
$detect = _getMimeDetect();
$type = 'unknown';
switch ($detect) {
case 'finfo':
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if ($finfo) $type = finfo_file($finfo, $path);
break;
case 'mime_content_type':
$type = mime_content_type($path);
break;
case 'linux':
$type = exec('file -ib ' . escapeshellarg($path));
break;
case 'bsd':
$type = exec('file -Ib ' . escapeshellarg($path));
break;
default:
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$type = isset($mime[$ext]) ? $mime[$ext] : 'unknown';
}
// 修正 application/octet-stream 误判
if ($detect !== 'internal') {
$type = explode(';', $type)[0];
if ($type === 'application/octet-stream') {
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ($ext && isset($mime[$ext])) $type = $mime[$ext];
}
}
return $type;
}
// 测试
var_dump(_getMimeType('1.txt')); // 即使文件不存在,也会按扩展名返回 text/plain
php-fileinfo 扩展(PHP 5.3+ 内置,默认开启)。$_FILES['tmp_name'] 检测临时文件真实类型,防止伪造。