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