Get HTTP headers of any site using curl

Get all HTTP headers of any website with Curl. It is very simple as curl is a very powerful library of php. Look at the given code.

If you want to know more about curl, You may also want to take a look at Working of Curl.


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

    $agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    curl_close($ch);

    $data = explode("\n",trim($output));

    echo "<pre>";
    foreach($data as $part){
    $middle=explode(":",$part);
    if(trim($middle[0])!=''){
      if(stripos($middle[0],'HTTP') === false){
       echo "<b>".trim($middle[0])."</b>=>".trim($middle[1]);
      }else{
       echo "<b>Status</b>"."=>".trim($middle[0]);
      }
    }
    echo "\n";
    }
    echo "</pre>";


One thing to note here that to get only headers, set the status of CURLOPT_NOBODY to true otherwise bydefault it will return full body contents.

If you want to return the contents of body also you can omit this statement or set its status to false.
Get HTTP headers of any site using curl Get HTTP headers of any site using curl Reviewed by JS Pixels on April 29, 2012 Rating: 5

2 comments:

  1. Super thanks! I was looking for the better way to implement Curl to view the HTTP header and this is perfect :)

    ReplyDelete

Altaf Web. Powered by Blogger.