PHP + CURL: Get Returned Content Mime Type

Did you ever tried to get mime type of the returned content in CURL! I was writing a small application for something and thought to know the Content-Type (mime type) of the response data returned by CURL's exec(). Before thinking of anything else, I habitually started Goggling and found this article after few minutes. It is a completely big page about getting content type of web page grabbed in various ways. Function curl_getinfo() return lots of useful information about CURL transfer.

Just have a looks here to know better about the function: curl_getinfo().

- url
- content_type
- http_code"
- header_size
- request_size
- filetime
- ssl_verify_result
- redirect_count
- total_time
- namelookup_time
- connect_time
- pretransfer_time
- size_upload
- size_download
- speed_download
- speed_upload
- download_content_length
- upload_content_length
- starttransfer_time
- redirect_time

The function returns lots of other very useful information than only return headers. You may like to play with it.

curl_getinfo(curl resource) return all the mentioned data above. For specific info only, provide second parameters as CURLINFO_CONTENT_TYPE. Add the CURLINFO_ to above list and you will get needed data about that parameter.

Now, lets come to the point.

Get MimeType of Content returned by CURL in PHP

<?php
$ch = curl_init('http://o2.satya-weblog.com/wp-content/themes/simple/style.css');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
$content = curl_exec($ch);
if(!curl_errno($ch))
{
	$info = curl_getinfo($ch);
	echo 'Content type of returned data: ' . $info['content_type'];
	$info = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
	echo '<br>'. $info;
}
curl_close($ch);
?>

Output:

Content type of returned data:text/css

text/css

In the case of CSS and JavaScript content type, the content type returned is directly a mime type (text/css, application/JavaScript). However, in case of HTML page, I see that it is returning content type as "text/html; charset=utf-8" . Why is this so? Need to investigate. Therefore, the mentioned page has used for extracting mime type of content. Here is the code:

<?php
preg_match( '@([-w/+]+)(;s+charset=(S+))?@i', $content_type, $matches );
if ( isset( $matches[1] ) )
    $mime = $matches[1];
if ( isset( $matches[3] ) )
    $charset = $matches[3];
?>

I have added '-' to the their regex, so that it can return mime type like application/x-javascript also. Many Linux server can have JavaScript mime type set as application/x-javascript instead of just application/javascript.

  • # 1 - by Designer

    LAMP (Linux – Apache – MySQL – PHP)

    LAMP is a solution stack of Software which is an Opensource (Free) that is used to run Dynamic Websites or Servers.

    For more details: http://www.openwavecomp.com

Comments are open for an year period. Please, write here on Facebook page.