14

How can I retrieve the cookies from a Guzzle request / client, after a request has occurred?

$client = new Client([
    'base_uri' => 'www.google.com',
]);
$response = $client->request('GET', '/');
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286

3 Answers3

33

Read the docs, please. You have to use CookieJar class to work with cookies.

$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');

$cookieJar = $client->getConfig('cookies');
$cookieJar->toArray();
Alexey Shokov
  • 4,775
  • 1
  • 21
  • 22
  • 23
    Thank you for the answer. To be fair, the documentation doesn't mention how to access cookies from Guzzle. Only how to provide a CookieJar instance to a request. It doesn't even explain how to interact with a CookieJar instance. – kfriend Jun 04 '18 at 19:15
  • 1
    `getConfig` is deprecated by now. – Amit Shah Jan 05 '23 at 04:51
2

just updating this post.

In Guzzle version 8.0, the getConfig() method will be @deprecated. Read the docs.

You can get cookies, from sample code:

$client = new Client([
        'base_uri' => 'YOUR_URI',
    ]);
    
$response = $client->post('PATH');

$headerSetCookies = $response->getHeader('Set-Cookie');

$cookies = [];
foreach ($headerSetCookies as $key => $header) {
    $cookie = SetCookie::fromString($header);
    $cookie->setDomain('YOUR_DOMAIN');

    $cookies[] = $cookie;
}

$cookieJar = new CookieJar(false, $cookies);

For use, then:

$client->post('PATH', [
    'cookies' => $cookieJar
]);
Thiago Silva
  • 161
  • 1
  • 3
-2

You can also get the CookieJar from the response like this:

$client = new Client([
    'base_uri' => 'www.google.com',
    'cookies'  => true,
]);
$response = $client->request('GET', '/');
$cookieJar = $response->cookies();
$cookieArray = $cookieJar->->toArray();
Adam
  • 25,960
  • 22
  • 158
  • 247
  • 2
    I don't think there is a cookies() function. Perhaps there once was but now removed? I am also looking through version 7 source code and don't see one in addition to testing it and getting an error thrown about no such method existing. Just mentioning this in case anyone else tries using that method. Also the docs are pretty vague and not very clear. Even the comments in the source code of the Cookie classes are almost non-existent. In other parts the comments are very verbose and clear. Not sure why they skimped on Cookie code. – C Miller Nov 30 '22 at 18:04