php – 将cookie从浏览器传递到Guzzle 6客户端

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 将cookie从浏览器传递到Guzzle 6客户端脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 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 \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');

希望能帮助到你!

脚本宝典总结

以上是脚本宝典为你收集整理的php – 将cookie从浏览器传递到Guzzle 6客户端全部内容,希望文章能够帮你解决php – 将cookie从浏览器传递到Guzzle 6客户端所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。