PHP how can i check if a file is mp3 or image file

2020-01-23 12:27发布

how can i check if a file is an mp3 file or image file, other than check each possible extension?

11条回答
再贱就再见
2楼-- · 2020-01-23 12:47

To find the mime type of a file I use the following wrapper function:

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;
}
查看更多
欢心
3楼-- · 2020-01-23 12:48

For Images, I use:

    function is_image($path)
   {
    $a = getimagesize($path);
    $image_type = $a[2];

    if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP)))
    {
        return true;
    }
    return false;
    }
查看更多
Root(大扎)
4楼-- · 2020-01-23 12:52

You can use FileInfo module which is built into PHP since 5.3. If you are using a PHP version less than PHP 5.3, you can install it as a PECL extension:

After installation the finfo_file function will return file information.

PECL extension: http://pecl.php.net/package/fileinfo

PHP Documentation: http://www.php.net/manual/en/book.fileinfo.php

查看更多
我想做一个坏孩纸
5楼-- · 2020-01-23 12:53

try mime_content_type()

<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?> 

Output:

image/gif

text/plain

Or better use finfo_file() the other way is deprecated.

查看更多
你好瞎i
6楼-- · 2020-01-23 12:54

Native ways to get the mimetype:

For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_fopen()

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

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;
}
查看更多
登录 后发表回答