Home

Awesome

PHP Timeouts

An unresponsive service can be worse than a down one. It can tie up your entire system if not handled properly. All network requests should have a timeout.

Here’s how to add timeouts for popular PHP packages. All have been tested. The default is no timeout, unless otherwise specified. Enjoy!

Also available for Ruby, Python, Node, Go, and Rust

Build Status

Contents

Standard library

Packages

Standard Library

cURL

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);

No exception is raised. Use curl_error($ch) to check for a timeout.

Packages

guzzlehttp/guzzle

new GuzzleHttp\Client(['timeout'  => 1]);

Raises GuzzleHttp\Exception\ConnectException

opensearch-project/opensearch-php

$client = (new \OpenSearch\ClientBuilder())
    ->setConnectionParams(['client' => ['curl' => [CURLOPT_CONNECTTIMEOUT => 1, CURLOPT_TIMEOUT => 1]]])
    ->build();

Raises OpenSearch\Common\Exceptions\NoNodesAvailableException

predis/predis

new Predis\Client(['timeout' => 1, 'read_write_timeout' => 1]);

Default: 5s connect timeout

Raises Predis\Connection\ConnectionException

symfony/http-client

HttpClient::create(['timeout'  => 1]);

Raises Symfony\Component\HttpClient\Exception\TimeoutException

Don’t see a library you use?

Let us know. Even better, create a pull request for it.

Running the Tests

git clone https://github.com/ankane/php-timeouts.git
cd php-timeouts
composer install
php tests/server.php

To run all tests, use:

composer test

To run individual tests, use:

composer test -- --filter guzzle