Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guzzle 6: Get URL that was "resolved" from base_uri

Tags:

guzzle6

In Guzzle 3 you can get the resolved URL (without actually opening it) like this:

$client = new Client([
    'base_uri' => 'http://foo.com',
]);

$request = $client->get('bar.html');

echo $request->getUrl();

In Guzzle 6 this is not working anymore. Is there another way to get "http://foo.com/bar.html"?

like image 523
Thomas Landauer Avatar asked Nov 20 '25 00:11

Thomas Landauer


2 Answers

You can use the history middleware, works as advertised:

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;

$container = [];

$stack = HandlerStack::create();
$stack->push(Middleware::history($container));

$client = new Client([
    'base_uri' => 'http://foo.com',
    'handler' => $stack,
]);

$response = $client->request('GET', 'bar.html');

/* @var RequestInterface $request */
$request = $container[0]['request'];

echo $request->getUri();

For reference, see http://docs.guzzlephp.org/en/latest/testing.html#history-middleware.

like image 164
localheinz Avatar answered Nov 22 '25 03:11

localheinz


It is a bit late, but for the reference.

You can do it with \GuzzleHttp\Psr7\UriResolver::resolve($baseUri, $relUri);

It converts the relative URI into a new URI that is resolved against the base URI.

$baseUri and $relUri are instances of \Psr\Http\Message\UriInterfaceUriInterface.

like image 38
zstate Avatar answered Nov 22 '25 03:11

zstate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!