How can I track redirected requests?

You can enable tracking of redirected URIs and status codes via the track_redirects option. Each redirected URI and status code will be stored in the X-Guzzle-Redirect-History and the X-Guzzle-Redirect-Status-History header respectively.

The initial request’s URI and the final status code will be excluded from the results. With this in mind you should be able to easily track a request’s full redirect path.

For example, let’s say you need to track redirects and provide both results together in a single report:

  1. // First you configure Guzzle with redirect tracking and make a request
  2. $client = new Client([
  3. RequestOptions::ALLOW_REDIRECTS => [
  4. 'max' => 10, // allow at most 10 redirects.
  5. 'strict' => true, // use "strict" RFC compliant redirects.
  6. 'referer' => true, // add a Referer header
  7. 'track_redirects' => true,
  8. ],
  9. ]);
  10. $initialRequest = '/redirect/3'; // Store the request URI for later use
  11. $response = $client->request('GET', $initialRequest); // Make your request
  12. // Retrieve both Redirect History headers
  13. $redirectUriHistory = $response->getHeader('X-Guzzle-Redirect-History')[0]; // retrieve Redirect URI history
  14. $redirectCodeHistory = $response->getHeader('X-Guzzle-Redirect-Status-History')[0]; // retrieve Redirect HTTP Status history
  15. // Add the initial URI requested to the (beginning of) URI history
  16. array_unshift($redirectUriHistory, $initialRequest);
  17. // Add the final HTTP status code to the end of HTTP response history
  18. array_push($redirectCodeHistory, $response->getStatusCode());
  19. // (Optional) Combine the items of each array into a single result set
  20. $fullRedirectReport = [];
  21. foreach ($redirectUriHistory as $key => $value) {
  22. $fullRedirectReport[$key] = ['location' => $value, 'code' => $redirectCodeHistory[$key]];
  23. }
  24. echo json_encode($fullRedirectReport);