PHP curl timeout error detection

PHP curl timeout error detection

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Detecting Timeout Errors in PHP cURL

Handling HTTP requests reliably requires more than just executing a function; you need to interpret the return values correctly. When using curl_exec in PHP, the most common pitfall is assuming that a non-false result implies success. In reality, curl_exec returns an empty string on both successful responses and errors unless explicitly configured otherwise. Your current setup sets CURLOPT_RETURNTRANSFER to 1, which means you get data back even if something goes wrong. The challenge is distinguishing between a timeout and other failures like connection refused or invalid SSL certificates.

The primary mechanism for error detection in cURL is the return value of curl_exec. If the function returns false, an error has occurred. However, relying solely on this boolean check leaves you blind to the specific nature of that error. You must call curl_errno() and curl_error() immediately after execution to retrieve the numeric error code and its human-readable description.

To specifically handle timeouts, you need to look for the CURLE_OPERATION_TIMEDOUT error code. This constant represents a timeout that occurred during an operation. However, cURL distinguishes between connection timeouts and read timeouts. Your current configuration sets CURLOPT_CONNECTTIMEOUT, which only limits the time spent establishing the connection. If the server takes too long to send the first byte of data, or if the download itself exceeds your limit, you need CURLOPT_TIMEOUT (or CURLOPT_TIMEWAIT) configured as well.

Here is a robust pattern for checking errors and distinguishing timeouts:

$ch = curl_init();
$url = $url;
$timeout = 5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
// It is also good practice to set a total timeout to prevent hanging on slow responses
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 

$data = curl_exec($ch);

if (curl_errno($ch) === false) {
    // No error occurred
} else {
    $errno = curl_errno($ch);
    $errstr = curl_error($ch);

    if ($errno === CURLE_OPERATION_TIMEDOUT) {
        // This covers both connect and read timeouts depending on which option was hit
        throw new Exception("Request timed out: " . $errstr);
    } else {
        throw new Exception("CURL Error {$errno}: " . $errstr);
    }
}

curl_close($ch);

There is a subtle distinction in error codes depending on the version of PHP and cURL being used. In older versions or specific configurations, CURLE_OPERATION_TIMEDOUT might be reported differently for connection vs. read timeouts, but modern implementations generally consolidate this into a single operational timeout code once either limit is breached.

Another approach involves checking the HTTP status code returned in the response header, but only if you successfully established a connection. If curl_exec returns false due to a timeout, there will be no headers to parse. You can check for headers using curl_getinfo($ch, CURLINFO_HTTP_CODE) after execution, but this should only be done if curl_errno() confirms the request was not aborted.

A common mistake developers make is forgetting to close the handle or failing to reset options between requests in a loop. While your example includes curl_close, ensure that error handling logic is present before closing the resource. Closing the handle does not clear error codes; you must inspect the state immediately after execution.

For production environments, consider wrapping this logic in a helper class. This prevents the repetition of boilerplate code and centralizes timeout configuration. If you are building a larger application framework where such utilities are essential, resources like LaravelCompany offer insights into structured API client patterns that might abstract these low-level details further. However, understanding the underlying cURL behavior remains crucial for debugging when those abstractions fail or behave unexpectedly.

Ultimately, distinguishing timeouts from other failures requires inspecting the numeric error code returned by curl_errno(). Relying on string matching of the error message is fragile because error strings can vary between operating systems and cURL versions. By checking for CURLE_OPERATION_TIMEDOUT explicitly, your application can react appropriately—perhaps by retrying with an exponential backoff strategy or logging the specific latency issue without masking other potential connection problems.

Our network