By default, Guzzle, a PHP HTTP client library, automatically follows HTTP redirects. However, you can disable automatic redirect following or customize its behavior with the help of the allow_redirects
option.
To enable redirect following, make sure you have the Guzzle library installed via Composer:
composer require guzzlehttp/guzzle
Now, you can create a basic Guzzle request with redirect following:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'http://example.com');
$body = $response->getBody()->getContents();
echo $body;
In the above example, the GET
request will automatically follow redirects until it reaches the final response. The response content is then retrieved and echoed.
If you want to customize or disable redirect following, you can use the allow_redirects
option when creating the Guzzle client:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$client = new Client([
RequestOptions::ALLOW_REDIRECTS => [
'max' => 5, // maximum number of redirects to follow
'strict' => true, // enable strict redirect RFC compliance
'referer' => true, // add the Referer header when redirecting
'protocols' => ['http', 'https'], // allowed redirect protocols
],
]);
With the allow_redirects
option, you can specify various settings such as the maximum number of redirects to follow, whether to strictly adhere to the RFC for redirects, whether to add the Referer header, and which protocols to allow for redirection.
By default, Guzzle uses a maximum redirect limit of 5 and enables strict RFC compliance. Referer headers are not automatically added, and all protocols are allowed for redirection.
By configuring the allow_redirects
option as per your needs, you can easily control the behavior of redirect following in Guzzle requests.