How to get MIME type of a file in PHP 5.5?

旧城冷巷雨未停 提交于 2019-11-27 08:34:12

Make use of the finfo() functions.

A simple illustration:

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, "path/to/image_dir/image.gif");
finfo_close($finfo);

OUTPUT :

image/gif

Note : Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.

I've spent too much time trying to get the finfo functions to work, properly. I finally just ended up creating my own function to match the file extension to any array of mime types. It's not a full-proof way of assuring that the files are truly what the extension denotes them to be, but that problem can be mitigated by how you process I/O of said files on your server(s).

function mime_type($file) {

    // there's a bug that doesn't properly detect
    // the mime type of css files
    // https://bugs.php.net/bug.php?id=53035
    // so the following is used, instead
    // src: http://www.freeformatter.com/mime-types-list.html#mime-types-list

    $mime_type = array(
        "3dml" => "text/vnd.in3d.3dml",
        "3g2" => "video/3gpp2",
        "3gp" => "video/3gpp",
        "7z" => "application/x-7z-compressed",
        "aab" => "application/x-authorware-bin",
        "aac" => "audio/x-aac",
        "aam" => "application/x-authorware-map",
        "aas" => "application/x-authorware-seg",
        "abw" => "application/x-abiword",
        "ac" => "application/pkix-attr-cert",
        "acc" => "application/vnd.americandynamics.acc",
        "ace" => "application/x-ace-compressed",
        "acu" => "application/vnd.acucobol",
        "adp" => "audio/adpcm",
        "aep" => "application/vnd.audiograph",
        "afp" => "application/vnd.ibm.modcap",
        "ahead" => "application/vnd.ahead.space",
        "ai" => "application/postscript",
        "aif" => "audio/x-aiff",
        "air" => "application/vnd.adobe.air-application-installer-package+zip",
        "ait" => "application/vnd.dvb.ait",
        "ami" => "application/vnd.amiga.ami",
        "apk" => "application/vnd.android.package-archive",
        "application" => "application/x-ms-application",
        // etc...
        // truncated due to Stack Overflow's character limit in posts
    );

    $extension = \strtolower(\pathinfo($file, \PATHINFO_EXTENSION));

    if (isset($mime_type[$extension])) {
        return $mime_type[$extension];
    } else {
        throw new \Exception("Unknown file type");
    }

}

Edit:

I'd like to address Davuz's comment (since it keeps getting up-voted) and remind everyone that I put in the pseudo disclaimer at the top that this isn't "full-proof." So, please keep that in mind when considering the approach I've offered in my answer.

Anuga

mime_content_type() is not deprecated and works fine.

Why is mime_content_type() deprecated in PHP?

http://php.net/manual/en/function.mime-content-type.php

As of PHP 5.3, it's even built-in.

$finfo = finfo_open(FILEINFO_MIME_TYPE); should do it.

Taken from the php.net docs. Your function is deprecated and probably already removed.

http://www.php.net/manual/en/function.finfo-file.php

You should understand that file_get_contents will upload whole file to the memory, it is not good way to get only mime type. You don't need to use buffer method and file_get_contents function in this case.

To prevent any errors and warnings, better do like this.

$filename = 'path to your file';

if (class_exists('finfo')) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (is_object($finfo)) {
        echo $finfo->file($filename);
    }
} else {
    echo 'fileinfo did not installed';
}

Also you should know $finfo->file will throw PHP Warning if it fail.

If fileinfo is not installed properly, and you have a fresh version of PHP, you can get mime type from headers.

You can use cURL to get mime type from headers.

    $ch = curl_init();
    curl_setopt_array($ch, array(
            CURLOPT_HEADER => true,
            CURLOPT_NOBODY => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 1,
            CURLOPT_URL => $link)
    );

    $headers = curl_exec($ch);
    curl_close($ch);

    if (preg_match('/Content-Type:\s(.*)/i', $headers, $matches)) {
        echo trim($matches[1], "\t\n\r");
    }else {
        echo 'There is no content type in the headers!';
    }

Also you can use get_headers function, but it more slow than cURL request.

$url = 'http://www.example.com';

$headers = get_headers($url, 1);

echo $headers['Content-Type'];

Get the image size using:

$infFil=getimagesize($the_file_name);

and

echo $infFil["mime"]

The getimagesize returns an associative array which have a MIME key and obviously the image size too

I used it and it works

I use the MimeTypeTool from Bat (https://github.com/lingtalfi/Bat)

It uses fileinfo if available, and defaults back to an "extension => mime type" mapping otherwise.

This is the best solution I found by combining two very good posts

// Thanks to http://php.net/manual/en/function.mime-content-type.php#87856

function getMimeContentType($filename, $ext)
{
    if(!function_exists('mime_content_type'))
    {
        if($mime_types = getMimeTypes())
        {
            if (array_key_exists($ext, $mime_types))
            {
                return $mime_types[$ext];
            }
            elseif (function_exists('finfo_open'))
            {
                $finfo  = finfo_open(FILEINFO_MIME);
                $mimetype = finfo_file($finfo, $filename);
                finfo_close($finfo);
                return $mimetype;
            }
        }
        return 'application/octet-stream';
    }
    return mime_content_type($filename);
}

// Thanks to http://php.net/manual/en/function.mime-content-type.php#107798

function getMimeTypes()
{
    $url = 'http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types';

    $mimes = array();
    foreach(@explode("\n",@file_get_contents($url)) as $x)
    {
        if(isset($x[0]) && $x[0]!=='#' && preg_match_all('#([^\s]+)#', $x, $out) && isset($out[1]) && ($c = count($out[1])) > 1)
        {
                for($i=1; $i < $c; $i++)
            {
                    $mimes[$out[1][$i]] = $out[1][0];
            }
        }
    }
    return (@sort($mimes)) ? $mimes : false;
}

Use it link this:

$filename = '/path/to/the/file.pdf';
$ext = strtolower(array_pop(explode('.',$filename)));
$content_type = getMimeContentType($filename, $ext);

Will continue to work even if the mime_content_type function is no longer supported in php.

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