How can I get the mime type in PHP

折月煮酒 提交于 2019-12-02 01:07:12

You could try finfo_file - it returns the mime type.

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

I use the following function, which is a wrapper for the 3 most common methods:

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

$_FILES['file']['type'] comes from the browser that uploads the file so you can't rely on this value at all.

Check out finfo_file for identifying file types based on file content. The extension of the file is also unreliable as the user could upload malicious code with an mp3 extension.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!