13

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

4

2 回答 2

11

尝试类似:

/**
 * 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');
于 2015-11-13T20:53:44.310 回答
3

我认为您现在可以使用以下方法简化此操作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]);
于 2018-10-22T20:38:24.530 回答