我有一个PHP webapp,它向另一个PHP API发出请求。我使用Guzzle发出http请求,将$_COOKIES
数组传递给$options['cookies']
。我这样做是因为API使用与前端应用程序相同的Laravel会话。我最近升级到Guzzle 6,我无法再将$_COOKIES
传递给$options['cookies']
(我收到有关需要分配CookieJar
的错误)。我的问题是,如何将我在浏览器中显示的任何cookie移交给我的Guzzle 6客户端实例,以便它们包含在我的API请求中?
答案 0 :(得分:8)
尝试类似:
/**
* 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]);
以及如何再次将它们拿出来:
$newCookies = $guzzleResponse->getHeader('set-cookie');
希望它有所帮助!
答案 1 :(得分:1)
我认为您现在可以使用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]);