Transferring cookies from the browser to the Guzzle 6 client

I have a PHP webapp that makes requests to another PHP API. I use Guzzle to create http requests by passing the $_COOKIES to $options['cookies'] . I do this because the API uses the same Laravel session as the external application. I recently upgraded to Guzzle 6, and I can no longer pass $_COOKIES to $options['cookies'] (I get an error when I need to set a CookieJar ). My question is, how can I transfer all cookies that I have in my browser to my Guzzle 6 client instance so that they are included in the request to my API?

+8
source share
2 answers

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 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'); 

Hope this helps!

+7
source

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

 use GuzzleHttp\Cookie\CookieJar; use GuzzleHttp\Client; // grab the cookies from the existing user 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]); 
0
source

All Articles