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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31882080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:08:52  来源:igfitidea点击:

Passing cookies from browser to Guzzle 6 client

phplaravelcookiesguzzleguzzle6

提问by Thelonias

I have a PHP webapp that makes requests to another PHP API. I use Guzzle to make the http requests, passing the $_COOKIESarray 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 $_COOKIESto 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?

我有一个 PHP webapp,它向另一个 PHP API 发出请求。我使用 Guzzle 发出 http 请求,将$_COOKIES数组传递给$options['cookies']. 我这样做是因为 API 使用与前端应用程序相同的 Laravel 会话。我最近升级到 Guzzle 6 并且我不能再传递$_COOKIES$options['cookies'](我收到一个关于需要分配一个的错误CookieJar)。我的问题是,如何将浏览器中存在的任何 cookie 移交给我的 Guzzle 6 客户端实例,以便将它们包含在对我的 API 的请求中?

采纳答案by Richy B.

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

回答by Dylan Pierce

I think you can simplify this now with CookieJar::fromArray:

我认为您现在可以使用以下方法简化它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]);