Guzzle: Getting redirected URL

Created on 22 Apr 2018  路  4Comments  路  Source: guzzle/guzzle

I'm trying to get the final URL after redirection
'''php
use GuzzleHttp\Client;
use GuzzleHttpTransferStats;

$client = new Client(
[
'allow_redirects'=>true,
]);
$client->get('http://example.com',[
'on_stats'=>function (TransferStats $stats){
echo $stats->getEffectiveUri();
},
]);
'''
It returned null but the '''php get() ''' retrieve the page data of redirected url

kinsupport

Most helpful comment

more simply with 6.3.3

$this->client    = new Client(['allow_redirects' => ['track_redirects' => true]]);
$response        = $this->client->get($urlProduct);
$headersRedirect = $response->getHeader(\GuzzleHttp\RedirectMiddleware::HISTORY_HEADER);
var_dump($headersRedirect);

All 4 comments

Using this code (on Guzzle 6.3.3):

$client = new GuzzleHttp\Client([
    'allow_redirects'=>true,
]);

$res = $client->get(
    'http://www.indishare.me/r7ogprg7eznr',
    [
        'on_stats'=>function (GuzzleHttp\TransferStats $stats){
            echo $stats->getEffectiveUri()."\n";
        },
    ]
);

I get the following result:

http://www.indishare.me/r7ogprg7eznr
http://www.indishare.me/f/skjbzt-e6cj4wnq16qye

Which version of guzzle do you use? Which handler (curl or stream)?

I'm sorry. I was confused by a snippet from SO. But it is working. The mistake was this .

$stats->getHandlerStats()['redirect_url'];

and Instead of echoing I dumped the value of php $stats->getEffectiveUri() and got output of the class;
However thanks :)

At this moment this is my code(functional)

$redir = '';
$res = $client->get($this->url,[
'on_stats'=>function (TransferStats $stats) use(&$redir){
$redir = (string) $stats->getEffectiveUri();
}
]);
echo $redir;//OK

more simply with 6.3.3

$this->client    = new Client(['allow_redirects' => ['track_redirects' => true]]);
$response        = $this->client->get($urlProduct);
$headersRedirect = $response->getHeader(\GuzzleHttp\RedirectMiddleware::HISTORY_HEADER);
var_dump($headersRedirect);
Was this page helpful?
0 / 5 - 0 ratings