How to request just the response headers with cURL

Here is the cURL config to request just the response headers with the cURL library

/*
Outputs an array of response headers similar to:
Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Server: nginx
    [2] => Date: Wed, 21 Aug 2013 15:04:45 GMT
    [3] => Content-Type: text/html; charset=utf-8
    [4] => Connection: keep-alive
    [5] => Vary: Accept-Encoding
    [6] => Vary: Cookie
    [7] => Set-Cookie: wordpress_homepage=existing; expires=Thu, 05-Sep-2013 15:04:45 GMT
    [8] => 
    [9] => 
)
*/
function get_url_headers( $url ) {
    $curl = curl_init();
    
    curl_setopt( $curl, CURLOPT_URL, $url );
    curl_setopt( $curl, CURLOPT_FILETIME, true );
    curl_setopt( $curl, CURLOPT_NOBODY, true );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $curl, CURLOPT_HEADER, true );
       
    $headers = curl_exec( $curl );
    $headers = explode( "\r\n", $headers );
    
    curl_close($curl);
    
    return $headers;
}

This function will return the response headers in an array. This will allow you to easily iterate through the headers to check the response status and/or if a particular header is set.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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