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.

Take a look at the following piece of code.

<?php

//The URL we want to send a HTTP request to.
//In this case, it is a script on my local machine.
$url = 'http://localhost/tester/log.php';

//Initiate cURL
$ch = curl_init($url);

//Tell cURL that it should only spend 10 seconds
//trying to connect to the URL in question.
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

//A given cURL operation should only take
//30 seconds max.
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

//Tell cURL to return the response output as a string.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Execute the request.
$response = curl_exec($ch);

//Did an error occur? If so, dump it out.
if(curl_errno($ch)){
    throw new Exception(curl_error($ch));
}

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. In other words, if we connect, but the server takes too long to respond in full, then cURL should call it a day and stop waiting.

Testing the cURL timeout.

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 local 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!