PHP: Error handling with cURL

cURL is an extremely useful tool for any developer that is interested in sending HTTP requests via a server.

Some examples of its usefulness:

Although you can easily request external content via the function file_get_contents, cURL is much more valuable in the sense that it allows you to detect and handle certain errors.

Let’s take the following example:

As you can see, I’ve setup a very simple GET request that returns the contents of a website called Unfortunately, my code doesn’t take into account the fact that the cURL request could fail (for any number of different reasons).

This is where curl_errno comes in.

The function curl_errno will return the number 0 (zero) if the request was successful. This allows us to figure out whether or not an error has occured. Simple example:

If an error exists, we print it out on to the page using the function curl_error.

Throwing Exceptions

In certain situations, you might want to throw an exception if a cURL request has failed. For this example, let us pretend that we have an object function called get:

As you can see, the function above will attempt to send a GET request to a given URL. If the request fails and a cURL error exists, PHP will throw an Exception. If all goes well, it will return the content of the URL that was requested.

This allows us to handle the request like so:

In the above piece of code, we use a TRY-CATCH block. If we do not want our application to continue after a failed HTTP request, we can omit the TRY-CATCH block and let our Exception Handler deal with.

Facebook Comments