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

时间:2015-08-07 16:01:03

标签: php laravel cookies guzzle guzzle6

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

2 个答案:

答案 0 :(得分:8)

尝试类似:

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

希望它有所帮助!

答案 1 :(得分:1)

我认为您现在可以使用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]);