PHP如何检查文件是mp3还是图像文件?

kmu*_*nky 24 php mime-types

我如何检查文件是否是mp3文件或图像文件,而不是检查每个可能的扩展名?

Gor*_*don 30

获取mimetype的本机方法:

对于PHP <5.3,使用mime_content_type()
对于PHP> = 5.3,使用finfo_fopen()

获取MimeType的替代方法是exif_imagetypegetimagesize,但这些依赖于安装了适当的库.此外,他们可能只返回图像mimetypes,而不是magic.mime中给出的整个列表.

如果您不想打扰系统上的可用内容,只需将所有四个函数包装到一个代理方法中,该方法将函数调用委托给任何可用的函数,例如

function getMimeType($filename)
{
    $mimetype = false;
    if(function_exists('finfo_fopen')) {
        // open with FileInfo
    } elseif(function_exists('getimagesize')) {
        // open with GD
    } elseif(function_exists('exif_imagetype')) {
       // open with EXIF
    } elseif(function_exists('mime_content_type')) {
       $mimetype = mime_content_type($filename);
    }
    return $mimetype;
}
Run Code Online (Sandbox Code Playgroud)


Pek*_*ica 24

您可以使用标识图像文件getimagesize.

要了解有关MP3和其他音频/视频文件的更多信息,我建议使用php-mp4info getID3().

  • 你是说我应该检查一个文件是不是一个图像使用getimagesize之类的东西:if(!getimagesize(path)){print'这个文件不是图像!';}?和getimagesize(); 如果文件不是图像,则返回false? (2认同)

Ali*_*xel 6

要查找文件的mime类型,我使用以下包装函数:

function Mime($path)
{
    $result = false;

    if (is_file($path) === true)
    {
        if (function_exists('finfo_open') === true)
        {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            if (is_resource($finfo) === true)
            {
                $result = finfo_file($finfo, $path);
            }

            finfo_close($finfo);
        }

        else if (function_exists('mime_content_type') === true)
        {
            $result = preg_replace('~^(.+);.*$~', '$1', mime_content_type($path));
        }

        else if (function_exists('exif_imagetype') === true)
        {
            $result = image_type_to_mime_type(exif_imagetype($path));
        }
    }

    return $result;
}
Run Code Online (Sandbox Code Playgroud)