Search code examples
phpcurlmp3mime-typescontent-type

Will the CURLINFO_CONTENT_TYPE be the content type of the last url


I'm trying to test an mp3 file on a remote server and see if the content type is of media. I am already using CURLOPT_FOLLOWLOCATION but does that mean the CURLINFO_CONTENT_TYPE will be for the last location. I tried it out on a url and it said it wasn't valid, but once I went to the url it streamed out to me. I got most of this code from https://stackoverflow.com/a/12733693 and added some tweaks but now I fear its not always giving the correct result. How can I get the content type of the last url?

function mp3URLIsValid($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_FILETIME, true);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $header = curl_exec($curl);
    $info = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
    curl_close($curl);

    $mp3_mimes = array('audio/mpeg','application/octet-stream','application/mp3','audio/mpeg3','audio/x-mpeg-3');
    if (in_array($info, $mp3_mimes)) {
        return true;
    }
    return false;
}

Solution

  • After testing I figured out the content type may be an array with the first set to text and the second audio/mpeg. So I used php's get_header method to extract the info:

    function mp3URLIsValid($url){
        $headers = get_headers($url, 1);
        $type = $headers["Content-Type"];
        $mp3_mimes = array('audio/mpeg','application/octet-stream','application/mp3','audio/mpeg3','audio/x-mpeg-3');
    
        if(is_array($type)){
            foreach($type as $ntype){
                if (in_array($ntype, $mp3_mimes)) {
                return true;
                }
            }
        }else{
            if (in_array($type, $mp3_mimes)) {
                return true;
            }
        }
        return false;
    }