如何在PHP中获取mime类型

时间:2010-09-12 00:25:18

标签: php mime mime-types

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

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

我可以采用哪种方式(而且我不能访问shell命令)?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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;
}

答案 2 :(得分:2)

$ _ FILES ['file'] ['type']来自上传文件的浏览器,因此您根本不能依赖此值。

根据文件内容查看finfo_file以识别文件类型。由于用户可以使用mp3扩展程序上传恶意代码,因此文件的扩展名也不可靠。