Check to see if a HTTP resource exists with PHP

In certain circumstances, a developer might need to check if a HTTP resource exists before they attempt to use it. It could be an image that they expect to exist on a remote server or a website link that a user has copied and pasted into a form field.

Unfortunately, many developers are quite wasteful when it comes to this sort of thing. Instead of purely focusing their efforts on checking the status code of the resource, they’ll attempt to download it, 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:

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

Using cURL

One of the great things about cURL is that is that it has an option called CURLOPT_NOBODY, which allows you 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 metainformation 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 metainformation 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. In PHP, this type of request can be performed like so:

As you can probably imagine, downloading a large video with PHP just so you can confirm its existence would be insane!

Facebook Comments