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

Ale*_*zzi 24 php filenames mime file-type mime-types

是否有一个快速和脏的PHP类型映射到我可以使用的PHP扩展?

cha*_*aos 22

不是内置的,但是推出自己的内容并不是非常困难:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • @ JorgeB.G.那要求文件存在,不是吗? (7认同)
  • 我认为这是一个古老的答案.现在你应该使用`fileinfo` http://www.php.net/manual/en/ref.fileinfo.php (5认同)

Jor*_*ata 6

您可以使用mime_content_type但不推荐使用.fileinfo改为使用:

function getMimeType($filename) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $filename);
    finfo_close($finfo);
    return $mime;
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:`finfo_file()`和`mime_content_type()`要求该文件存在. (9认同)
  • 值得注意的是,OP实际上要求将MIME类型*映射到*文件扩展名.这仍然涵盖了最常见的用例(也可能是OP所面临的用例),因此它当然值得存在并且我已经对它进行了操作,但它并非*严格地回答了被迂回提出的问题.解释. (4认同)
  • 在哪里说它被弃用了? (4认同)