How can I get the mime type in PHP

大城市里の小女人 提交于 2020-01-30 06:52:45

问题


I am writing a script and I need to correctly (I think some mime types can be different from their extensions) get the mime types of files (the files can be of any type).

Web hosting company in use does not have mime_content_type() and is still (don't know which year they will be fixing it) promising to fix the PECL alternative.

Which other way can I go about it (and I don;t have access to shell commands)?


回答1:


You could try finfo_file - it returns the mime type.

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




回答2:


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



回答3:


$_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.



来源:https://stackoverflow.com/questions/3693245/how-can-i-get-the-mime-type-in-php

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