How to get all intermediary redirects using Symfony HttpClient

Viewed 628

How to get the url of all redirects using HttpClient?

Here is an example:

  1. http://example.com/page 301 redirects to:
  2. http://www.example.com/page 302 redirects to:
  3. http://www.example.com/page/
$response = $this->httpClient->request('GET', 'http://example.com/page');
$content = $response->getContent(false);    
$ary = $response->getInfo();

Only in the '[debug]' part of the getInfo I can see:

Issue another request to this URL: 'http://www.example.com/page'
...
Issue another request to this URL: 'http://www.example.com/page/'

Is there a way to retrieve the URLs of the redirects without parsing the debug text?

1 Answers

you can intercept redirects by setting the max_redirects parameter:

try {
    $this->httpClient->request('GET', 'http://example.com/page', ['max_redirects' => 0])->getContent();
    // not redirected
} catch (RedirectionException $e) {
    $redirectUrl = $e->getResponse()->getInfo()['redirect_url'];
}
Related