How to set a timeout for a Guzzle request in PHP?

To set a timeout for a Guzzle request in PHP, you can make use of the timeout configuration option in the request options array. Here's an example:

use GuzzleHttp\Client; $client = new Client(); try { $response = $client->request('GET', 'https://example.com', [ 'timeout' => 5, // Set the timeout in seconds ]); // Process the response as needed $statusCode = $response->getStatusCode(); $body = $response->getBody()->getContents(); // ... } catch (\GuzzleHttp\Exception\GuzzleException $e) { // Handle any Guzzle exceptions here echo $e->getMessage(); }

In the above example, the timeout is set to 5 seconds using the 'timeout' => 5 option in the request options array. If the request takes longer than the specified timeout, a GuzzleHttp\Exception\RequestException will be thrown. You can catch and handle such exceptions as shown in the catch block.

Make sure to include the use GuzzleHttp\Client; statement at the beginning of your code to import the GuzzleHttp client class.