13

I have a PHP webapp that makes requests to another PHP API. I use Guzzle to make the http requests, passing the $_COOKIES array to $options['cookies']. I do this because the API uses the same Laravel session as the frontend application. I recently upgraded to Guzzle 6 and I can no longer pass $_COOKIES to the $options['cookies'] (I get an error about needing to assign a CookieJar). My question is, how can I hand off whatever cookies I have present in the browser to my Guzzle 6 client instance so that they are included in the request to my API?

Richy B.
  • 1,619
  • 12
  • 20
Thelonias
  • 2,918
  • 3
  • 29
  • 63

2 Answers2

12

Try something like:

/**
 * First parameter is for cookie "strictness"
 */
$cookieJar = new \GuzzleHttp\Cookie\CookieJar(true);
/**
  * Read in our cookies. In this case, they are coming from a
  * PSR7 compliant ServerRequestInterface such as Slim3
  */
$cookies = $request->getCookieParams();
/**
  * Now loop through the cookies adding them to the jar
  */
 foreach ($cookies as $cookie) {
           $newCookie =\GuzzleHttp\Cookie\SetCookie::fromString($cookie);
           /**
             * You can also do things such as $newCookie->setSecure(false);
            */
           $cookieJar->setCookie($newCookie);
 }
/**
 * Create a PSR7 guzzle request
 */
$guzzleRequest = new \GuzzleHttp\Psr7\Request(
                   $request->getMethod(), $url, $headers, $body
        );
 /**
  * Now actually prepare Guzzle - here's where we hand over the
  * delicious cookies!
  */
 $client = new \GuzzleHttp\Client(['cookies'=>$cookieJar]);
 /**
  * Now get the response
  */
 $guzzleResponse = $client->send($guzzleRequest, ['timeout' => 5]);

and here's how to get them out again:

$newCookies = $guzzleResponse->getHeader('set-cookie');
DharmanBot
  • 1,066
  • 2
  • 6
  • 10
Richy B.
  • 1,619
  • 12
  • 20
3

I think you can simplify this now with CookieJar::fromArray:

use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Client;

// grab the cookies from the existing user's session and create a CookieJar instance
$cookies = CookieJar::fromArray([
     'key' => $_COOKIE['value']
], 'your-domain.com');
// create your new Guzzle client that includes said cookies
$client = new Client(['cookies' => $jar]);
Dylan Pierce
  • 4,313
  • 3
  • 35
  • 45
  • 2
    I think the cookies parameter is a boolean, not a reference to the `$jar`. Why is the documentation so vague for this cookie subject – hbogert Jan 09 '19 at 14:54
  • @hbogert, yes, it seems vague. Digging deeper the underlying source code says the above snippet works. Source code: https://github.com/guzzle/guzzle/blob/6b499cc5e2a7dd66c3131500a54abeec35383add/src/Client.php#L257-L261 https://github.com/guzzle/guzzle/blob/6b499cc5e2a7dd66c3131500a54abeec35383add/src/Middleware.php#L30-L36 Reason: https://stitcher.io/blog/what-is-array-plus-in-php – ssi-anik Oct 06 '21 at 06:20