Share via:

PHP: HEAD Request (cURL)

How to send a HTTP HEAD request using cURL in PHP.


Edited: 2019-11-09 05:15

PHP tutorial

Clients may send a HTTP HEAD request to check if a resource has been updated by comparing the response headers with a timestamp of a cached copy. If the cached copy is outdated, it will typically be invalidated, and a fresh GET request for the resource will be performed.

When a server responds to a HEAD request, the body part of the response should be excluded in order to save bandwidth. While useful for caching mechanisms, it is also useful when testing your HTTP headers.

In PHP, you can send a HEAD request through cURL by setting the CURLOPT_NOBODY option to true. In addition, we will also need to set CURLOPT_RETURNTRANSFER in order to have the response returned to us:

$url = '';
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);

// Output the response:
echo $response;

Note. The CURLOPT_HEADER option is used to include the response headers in the response. Without it, the response will be empty.

To test if PHP is in fact sending a HEAD request, you can use the verbose option:

curl_setopt($ch, CURLOPT_VERBOSE, true);

This will also allow you to extract other useful information, such as information about the TLS handshake and SSL certificate.