The last request type that we will look at is the HTTP HEAD request. Think of this one like an HTTP GET request but without any response body returned. The value in making this request is in ensuring that a resource is available prior to using it.
For instance, let’s say we scrape the content of a site and retrieve a series of image links, some of which have relative URLs in different formats, and others that are absolute URLs to the specific resource. We perform some logic to generate absolute URLs for the relative links so that we can use them from any site. We can then use HEAD requests to verify that the URLs that we have generated are valid and will return a resource prior to implementing them on a page. Since these requests don’t return back the actual image, we can perform this action quickly, as opposed to having to obtain the resource from a GET or simply integrating the image on a page without first ensuring that the link is valid.
A HEAD request in PHP is a simple process and mimics the corresponding GET request in many ways:
<?php $url = 'http://www.example.com/image.jpg'; $ch = curl_init($url); $options = array( CURLOPT_URL => $url, CURLOPT_HEADER => 1, CURLOPT_NOBODY => 1, CURLOPT_RETURNTRANSFER => 1 ); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); ?>
The important cURL parameter to note here is
CURLOPT_NOBODY. This parameter ensures that
the request being made is a HEAD request because no body content will be