php – 将cookie从浏览器传递到Guzzle 6客户端
发布时间:2020-12-13 13:28:05 所属栏目:PHP教程 来源:网络整理
导读:我有一个 PHP webapp,它向另一个 PHP API发出请求.我使用Guzzle来发出http请求,将$_COOKIES数组传递给$options [‘cookies’].我这样做是因为API使用与前端应用程序相同的Laravel会话.我最近升级到Guzzle 6,我不能再将$_COOKIES传递给$options [‘cookies’]
|
我有一个
PHP webapp,它向另一个
PHP API发出请求.我使用Guzzle来发出http请求,将$_COOKIES数组传递给$options [‘cookies’].我这样做是因为API使用与前端应用程序相同的Laravel会话.我最近升级到Guzzle 6,我不能再将$_COOKIES传递给$options [‘cookies’](我收到有关需要分配CookieJar的错误).我的问题是,如何将我在浏览器中显示的任何cookie移交给我的Guzzle 6客户端实例,以便它们包含在我的API请求中?
尝试以下方法:
/**
* First parameter is for cookie "strictness"
*/
$cookieJar = new GuzzleHttpCookieCookieJar(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 =GuzzleHttpCookieSetCookie::fromString($cookie);
/**
* You can also do things such as $newCookie->setSecure(false);
*/
$cookieJar->setCookie($newCookie);
}
/**
* Create a PSR7 guzzle request
*/
$guzzleRequest = new GuzzleHttpPsr7Request(
$request->getMethod(),$url,$headers,$body
);
/**
* Now actually prepare Guzzle - here's where we hand over the
* delicious cookies!
*/
$client = new GuzzleHttpClient(['cookies'=>$cookieJar]);
/**
* Now get the response
*/
$guzzleResponse = $client->send($guzzleRequest,['timeout' => 5]);
以下是如何让它们再次出现: $newCookies = $guzzleResponse->getHeader('set-cookie');
希望能帮助到你! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
