PHP: Check if an HTTP resource exists.

In this guide, we are going to show you how to check if an HTTP resource exists.

We can do this by sending a HEAD request to the URL.

HEAD requests are useful because they allow you to check the HTTP status of a resource without downloading the entire file.

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.

This can become a problem when they start dealing with large images and video files.

For example, they might attempt to download the resource by using the file_get_contents function:

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

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

The problem with this code is that it downloads an external image just to check if it exists.

Not only is this method slower, it is also wasting bandwidth.

Sending a HEAD request with PHP and cURL.

One of the great things about cURL 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, this means that a HEAD request will return the file’s header information without downloading the body.

In PHP, we can send a HEAD request using the cURL functions:

$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 sent a HEAD request and then validated the HTTP status code.

If the status code is 200, then we know that the remote file exists.

However, if the server responds with a 404, then we know that it does not exist.