How do I customize the timeout for a request in Guzzle?

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. When making requests over the network, it's often important to set timeouts to ensure that your application doesn't hang indefinitely if a server is slow to respond or there are network issues.

To customize the timeout in Guzzle, you can use the timeout option, which defines how long Guzzle will wait for a response from the server before giving up. There is also a connect_timeout option that defines how long Guzzle will wait while trying to connect to a server before timing out.

Here's an example of how to set both the timeout and connect_timeout options:

<?php
require 'vendor/autoload.php'; // Make sure to include the Guzzle autoloader

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

$client = new Client();

try {
    $response = $client->request('GET', 'http://httpbin.org/delay/3', [
        // Wait 2 seconds for the server to send a response
        'timeout' => 2.0,
        // Wait 1 second to connect to the server
        'connect_timeout' => 1.0
    ]);
    echo $response->getBody();
} catch (RequestException $e) {
    echo "There was a problem with your request: " . $e->getMessage();
}

In this example, the request is made to a URL that intentionally delays the response (http://httpbin.org/delay/3). The timeout is set to 2 seconds, meaning that if the server takes longer than that to send a complete response, a RequestException will be thrown. Similarly, if the connection to the server takes longer than 1 second, a RequestException will also be thrown due to the connect_timeout setting.

Keep in mind that if you're sending asynchronous requests using Guzzle's promise system, timeouts will work a bit differently. The timeout and connect_timeout options apply to each individual request, even when using promises.

If you need to set a default timeout for all requests made by a client, you can pass the options to the Guzzle client's constructor:

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://httpbin.org',
    // You can set any number of default request options.
    'timeout'  => 2.0,
    'connect_timeout' => 1.0,
]);

By setting these options, every request made with this client will inherit the specified timeout values unless they're overridden on a per-request basis.

Always be aware that setting a timeout can potentially lead to exceptions being thrown if the server or network is slow, so you should be prepared to handle those exceptions in your application.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon