如何在PHP中确定与MIME类型相关联的扩展名?

26

有没有一种快速而简单的方法,在PHP中将MIME类型映射到文件扩展名?


只想将“扩展名”映射到“MIME类型”,而不是反过来的人,应该注意现在已经内置了支持,他们应该利用它 - 参见Jorge's answer,而不是接受的答案。 - Mark Amery
1
@MarkAmery,但是需要注意的是,finfo_file()要求文件存在。这并不总是正确的情况。Chaos的答案仍然更贴切于OP,并且8年后仍然有效。 - Wranorn
5个回答

23

虽然没有内置功能,但自己编写并不是特别难:

function system_extension_mime_types() {
    # Returns the system MIME type mapping of extensions to MIME types, as defined in /etc/mime.types.
    $out = array();
    $file = fopen('/etc/mime.types', 'r');
    while(($line = fgets($file)) !== false) {
        $line = trim(preg_replace('/#.*/', '', $line));
        if(!$line)
            continue;
        $parts = preg_split('/\s+/', $line);
        if(count($parts) == 1)
            continue;
        $type = array_shift($parts);
        foreach($parts as $part)
            $out[$part] = $type;
    }
    fclose($file);
    return $out;
}

function system_extension_mime_type($file) {
    # Returns the system MIME type (as defined in /etc/mime.types) for the filename specified.
    #
    # $file - the filename to examine
    static $types;
    if(!isset($types))
        $types = system_extension_mime_types();
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    if(!$ext)
        $ext = $file;
    $ext = strtolower($ext);
    return isset($types[$ext]) ? $types[$ext] : null;
}

function system_mime_type_extensions() {
    # Returns the system MIME type mapping of MIME types to extensions, as defined in /etc/mime.types (considering the first
    # extension listed to be canonical).
    $out = array();
    $file = fopen('/etc/mime.types', 'r');
    while(($line = fgets($file)) !== false) {
        $line = trim(preg_replace('/#.*/', '', $line));
        if(!$line)
            continue;
        $parts = preg_split('/\s+/', $line);
        if(count($parts) == 1)
            continue;
        $type = array_shift($parts);
        if(!isset($out[$type]))
            $out[$type] = array_shift($parts);
    }
    fclose($file);
    return $out;
}

function system_mime_type_extension($type) {
    # Returns the canonical file extension for the MIME type specified, as defined in /etc/mime.types (considering the first
    # extension listed to be canonical).
    #
    # $type - the MIME type
    static $exts;
    if(!isset($exts))
        $exts = system_mime_type_extensions();
    return isset($exts[$type]) ? $exts[$type] : null;
}

5
我认为这是一个旧回答。现在您应该使用 fileinfo,网址是http://www.php.net/manual/en/ref.fileinfo.php。 - Jorge Barata
7
需要文件存在,是吗? - danronmoon
1
@danronmoon。是的,它确实可以。 - Qix - MONICA WAS MISTREATED
我编写了一个小包,根据文件扩展名猜测MIME类型(如果文件不存在或无法访问):https://github.com/mzur/guess-mime - Mouagip

5

您可以使用mime_content_type,但它已经被弃用了。现在请使用fileinfo代替它:

function getMimeType($filename) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $filename);
    finfo_close($finfo);
    return $mime;
}

5
值得注意的是,OP实际上要求将MIME类型映射到文件扩展名。这仍然涵盖了最常见的用例(也可能是OP面临的用例),因此它确实值得存在,我已经点了+1,但从严格解释来看,它不是对所问问题的回答。 - Mark Amery
12
注意:finfo_file()mime_content_type()需要文件存在。 - Pang
7
它在哪里标明已被弃用? - Greg
除非$filename是一个可读的字符串,否则此操作将失败。它不能用于不对应服务器上文件的通用字符串。 - kloddant
小提示:不幸的是,这两个函数都无法提供正确的MIME类型,因为它们检查文件的魔数。也就是说,对于CSS/JS文件,你只会得到text/plain。具有讽刺意味的是,即使是PHP内置服务器也避免使用这些函数,并拥有自己的映射表:https://github.com/php/php-src/blob/d3c86527a5a64ea8fe8279e5099960ede7e3b731/sapi/cli/mime_type_map.h - Christian

4
你可能需要使用这个库:https://github.com/ralouphie/mimey 使用示例:
$mimes = new \Mimey\MimeTypes;

// Convert extension to MIME type:
$mimes->getMimeType('json'); // application/json

// Convert MIME type to extension:
$mimes->getExtension('application/json'); // json

这是因为提供的PHP函数质量似乎存在问题。

2

如果您只使用非常简单的图像扩展,并且需要一些非常简单的东西,那么我认为这已经足够了。

   switch($info['mime'])
   {
    case 'image/gif'    : $extension = 'gif';   break;
    case 'image/png'    : $extension = 'png';   break;
    case 'image/jpeg'   : $extension = 'jpg';   break;

    default :
        throw new ApplicationException('The file uploaded was not a valid image file.');
    break;
    }

0

使用此文件: https://github.com/ralouphie/mimey/blob/develop/mime.types.php

像这样:

$mimes=include('mime.types.php');

或者复制内容:

$mime= array (
  'mimes' => 
  array (
    'ez' => 
    array (
      0 => 'application/andrew-inset',
    ),
    'aw' => 
    array (
      0 => 'application/applixware',
    ),
    'atom' => 
    array (
      0 => 'application/atom+xml',
    ),
    'atomcat' => 
    array (
      0 => 'application/atomcat+xml',
    )

  ...

以及从流中获取的示例:

 $finfo = new \finfo(FILEINFO_MIME_TYPE);
 $mime=$finfo->buffer($data);
 $mimes=include(__DIR__."/mime.types.php");
 echo ($mime); //mime
 echo ($mimes['extensions'][$mime]); // file extension

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接