Cookies

Guzzle can maintain a cookie session for you if instructed using the cookies request option. When sending a request, the cookies option must be set to an instance of GuzzleHttp\Cookie\CookieJarInterface.

  1. // Use a specific cookie jar
  2. $jar = new \GuzzleHttp\Cookie\CookieJar;
  3. $r = $client->request('GET', 'http://httpbin.org/cookies', [
  4. 'cookies' => $jar
  5. ]);

You can set cookies to true in a client constructor if you would like to use a shared cookie jar for all requests.

  1. // Use a shared client cookie jar
  2. $client = new \GuzzleHttp\Client(['cookies' => true]);
  3. $r = $client->request('GET', 'http://httpbin.org/cookies');

Different implementations exist for the GuzzleHttp\Cookie\CookieJarInterface :

  • The GuzzleHttp\Cookie\CookieJar class stores cookies as an array.
  • The GuzzleHttp\Cookie\FileCookieJar class persists non-session cookies using a JSON formatted file.
  • The GuzzleHttp\Cookie\SessionCookieJar class persists cookies in the client session.

You can manually set cookies into a cookie jar with the named constructor fromArray(array $cookies, $domain).

  1. $jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
  2. [
  3. 'some_cookie' => 'foo',
  4. 'other_cookie' => 'barbaz1234'
  5. ],
  6. 'example.org'
  7. );

You can get a cookie by its name with the getCookieByName($name) method which returns a GuzzleHttp\Cookie\SetCookie instance.

  1. $cookie = $jar->getCookieByName('some_cookie');
  2. $cookie->getValue(); // 'foo'
  3. $cookie->getDomain(); // 'example.org'
  4. $cookie->getExpires(); // expiration date as a Unix timestamp

The cookies can be also fetched into an array thanks to the toArray() method. The GuzzleHttp\Cookie\CookieJarInterface interface extends Traversable so it can be iterated in a foreach loop.