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

标签 php mime mime-types filenames file-type

在我可以使用的 PHP 中,是否有一种快速而肮脏的 MIME 类型到扩展的映射?

最佳答案

不是内置的,但你自己的也不是很难:

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;
}

关于php - 如何确定与 PHP 中的 MIME 类型关联的扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1147931/

相关文章:

java - 从字节数组和 mime 类型转换为字符串/对象

security - 如何在 Amazon S3 上设置 "X-Content-Type-Options : nosniff"?

php - 如何在symfony save方法中获取原始值?

PHPExcel : generating error due to php output?

apache - 字体 MIME 类型的正确 Apache AddType 指令

python - 在 python 中添加一个 mimetype

ruby-on-rails - 带有两个扩展名的 rails Controller respond_to 格式(例如 tar.gz)

php - PHP 和 MySQL 的 Multi-Tenancy

php - 使用 PHP 从 Redis 中选择特定模式的所有关键数据

php - 如何在 PHP 中将电子邮件附件保存到服务器?