Check to see if a remote resource exists with PHP.

This is a guide on how to send HEAD requests with PHP and cURL.

In certain circumstances, you might need to check if a remote HTTP resource exists. For example, you might want to check if an image exists on a remote server without having to download it. Or perhaps you want to validate a website link to make sure that it isn’t returning a 404.

Unfortunately, many developers are quite wasteful when it comes to this sort of thing. Instead of checking the status code of the resource, they will attempt to download the entire file, even if they don’t actually need the resource in question.

More often than not, they’ll attempt to download the resource by using something like file_get_contents.

$resourceUrl = 'http://example.com/img/large-image-34.jpg';

$resourceExists = false;
if(file_get_contents($resourceUrl) !== false){
    $resourceExists = true;
}

The problem with this is that you’re downloading an image for the sole purpose of checking to see if it exists. Consequently, you are wasting bandwidth.

Furthermore, the code will actually take longer to execute.

Sending a HEAD request with PHP and cURL.

One of the great things about cURL is that is that it has an option called CURLOPT_NOBODY. Essentially, this option allows us to send a HEAD request.

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The meta information contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining meta information about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

Basically, a HEAD request will allow you to check to see if a resource exists without downloading the resource in question. It tells the server to return header information without the body.

In PHP, we can carry out a HEAD request like so.

$resourceUrl = 'http://example.com/vid/large-video.mp4';
$resourceExists = false;

$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

//200 = OK
if($statusCode == '200'){
    $resourceExists = true;
}

In the code above, we send a HEAD request and then validate the HTTP status code.  If the status code is 200, then we know that it exists. However, if the server responds with a 404, then we know that the resource does not exist.

Downloading an entire video with PHP just to confirm that it exists would be insane. Especially when we can just send a HEAD request instead.