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

前端之家收集整理的这篇文章主要介绍了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');

希望能帮助到你!

原文链接:https://www.f2er.com/php/137492.html

猜你在找的PHP相关文章