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

前端 未结 8 1897
鱼传尺愫
鱼传尺愫 2020-11-30 07:10

I am using mime_content_type() in PHP 5.5 to get a MIME type, but it throws fatal: error function not found.

How can I achieve this on PHP

8条回答
  •  既然无缘
    2020-11-30 07:55

    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'];
    

提交回复
热议问题