Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing cookies from browser to Guzzle 6 client

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

like image 782
Thelonias Avatar asked Aug 07 '15 16:08

Thelonias


2 Answers

I think you can simplify this now with 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]);
like image 56
Dylan Pierce Avatar answered Nov 06 '22 15:11

Dylan Pierce


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');
like image 38
Richy B. Avatar answered Nov 06 '22 15:11

Richy B.