PHP: Setting cURL timeout options.

This is a short guide on how to use the cURL timeout options in PHP. In certain cases, you may want to specify a timeout in order to prevent your HTTP request from taking too long.

There are two cURL timeout options that you need to know about. These options are slightly different from one another, so I will explain them now:

  • CURLOPT_CONNECTTIMEOUT: The maximum amount of seconds that cURL should spend attempting to connect to a given URL.
  • CURLOPT_TIMEOUT: The maximum amount of seconds it should take for all cURL operations to be carried out. i.e. The maximum amount of time that the request should take.

Lets take a look at the following piece of code:

In the code above, I set CURLOPT_CONNECTTIMEOUT to 10 seconds and I set CURLOPT_TIMEOUT to 30 seconds. This means:

  • cURL should only spend 10 seconds attempting to connect to the given URL. If it can’t connect after 10 seconds, a timeout should occur.
  • If it does connect successfully, it should only spend a maximum of 30 seconds executing the request. i.e. If we connect, but the server takes too long to respond in full, then cURL should call it a day and stop waiting.

To test this, I added some basic cURL error handling to the end of my script so that any cURL errors would result in an exception being thrown. The URL that I am sending a HTTP request to uses PHP’s sleep function to create a 40 second delay (which is higher than the 30 seconds limit that we set with CURLOPT_TIMEOUT). As a result, the following exception was thrown:

Uncaught exception ‘Exception’ with message ‘Operation timed out after 30015 milliseconds with 0 bytes received’

As you can see, the cURL timeout after 30,015 milliseconds, which is 30 seconds.

Hopefully this tutorial cleared a few things up for you!

Comments

comments