How to get HTTP headers from CURL response?

You can write a simple PHP curl program to download a page. Every HTTP response contains a Header and the contents. In most cases, you will be concerned more about the contents. By default, curl response will give you the contents. But you can also specify that you need the header using the option CURLOPT_HEADER in your program with the curl_setopt function

curl_setopt($curlHandle, CURLOPT_HEADER, true);

Let’s see the complete program which is also give here.


function downloadURL($URL) {
 if(!function_exists('curl_init')) {
 die ("Curl PHP package not installedn");

 /*Initializing CURL*/
 $curlHandle = curl_init();

 /*The URL to be downloaded is set*/
 curl_setopt($curlHandle, CURLOPT_URL, $URL);
 /*Return the HTTP headers*/
 curl_setopt($curlHandle, CURLOPT_HEADER, true);
 /*Now execute the CURL, download the URL specified*/
 $response = curl_exec($curlHandle);
 return $response;

echo downloadURL("");

Let’s execute the program

$ php download.php | less

The output of the program will be something like this

HTTP/1.1 200 OK
Server: Apache
X-Backend-Server: pp-web03
Vary: Accept-Encoding
Content-Type: text/html; charset=UTF-8
Date: Fri, 06 Aug 2010 15:32:00 GMT
Expires: Fri, 06 Aug 2010 01:42:00 GMT
Transfer-Encoding: chunked
X-Powered-By: PHP/5.2.9
X-Cache-Info: not cacheable; response has already expired

<!DOCTYPE html>
<html lang="en-US" dir="ltr">

As you can see that there is the HTTP header in the top of the response. You can see disabling the CURLOPT_HEADER to false

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s