Passing cookies from browser to Guzzle 6 client Passing cookies from browser to Guzzle 6 client laravel laravel

Passing cookies from browser to Guzzle 6 client


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


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