【问题标题】:How can I get the mime type in PHP如何在 PHP 中获取 mime 类型
【发布时间】:2011-04-11 05:32:37
【问题描述】:

我正在编写一个脚本,我需要正确(我认为某些 mime 类型可能与其扩展名不同)获取文件的 mime 类型(文件可以是任何类型)。

正在使用的网络托管公司没有mime_content_type(),并且仍然(不知道他们将在哪一年修复它)承诺修复 PECL 替代方案。

我还有什么其他方法可以解决(而且我无法访问 shell 命令)?

【问题讨论】:

  • 是时候更换您的托管服务提供商了。

标签: php mime mime-types


【解决方案1】:

$_FILES['file']['type'] 来自上传文件的浏览器,所以你根本不能依赖这个值。

查看finfo_file 以根据文件内容识别文件类型。该文件的扩展名也不可靠,因为用户可以上传带有 mp3 扩展名的恶意代码。

【讨论】:

    【解决方案2】:

    我使用以下函数,它是 3 种最常用方法的包装器:

    function Mime($path, $magic = null)
    {
        $path = realpath($path);
    
        if ($path !== false)
        {
            if (function_exists('finfo_open') === true)
            {
                $finfo = finfo_open(FILEINFO_MIME_TYPE, $magic);
    
                if (is_resource($finfo) === true)
                {
                    $result = finfo_file($finfo, $path);
                }
    
                finfo_close($finfo);
            }
    
            else if (function_exists('mime_content_type') === true)
            {
                $result = mime_content_type($path);
            }
    
            else if (function_exists('exif_imagetype') === true)
            {
                $result = image_type_to_mime_type(exif_imagetype($path));
            }
    
            return preg_replace('~^(.+);.+$~', '$1', $result);
        }
    
        return false;
    }
    

    【讨论】:

      【解决方案3】:

      您可以尝试 finfo_file - 它返回 mime 类型。

      http://php.net/manual/en/book.fileinfo.php

      【讨论】:

        猜你喜欢
        • 2014-06-10
        • 2011-03-12
        • 2013-10-04
        • 2014-10-03
        • 2016-05-19
        • 2011-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多