萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 精准获取文件 MIME 类型:多层级降级策略与扩展名备选方案

为什么不能只靠扩展名?

文件扩展名易伪造,且同一扩展名可能对应多种 MIME(如 .svg 既是 image/svg+xml 也可能是 text/xml)。可靠的做法是:优先检测文件魔数,次之用系统 file 命令,最后回退到扩展名映射表。

分层检测策略

  1. finfo (Fileinfo 扩展):PHP 官方推荐,基于 libmagic,准确率最高。
  2. mime_content_type():旧版兼容函数,内部也调用 magic 库。
  3. Linux/BSD file -i/-ib:调用系统命令,需 exec 权限,适合无扩展环境。
  4. 内置扩展名映射表:兜底方案,覆盖常见 100+ 格式。

完整实现代码

<?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'] 检测临时文件真实类型,防止伪造。
  • 对用户上传文件,除 MIME 检测外,还应做:尺寸限制、图片重绘、病毒扫描、存储路径随机化。
copyright © 萬盛學電腦網 all rights reserved