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
.
// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
'cookies' => $jar
]);
You can set cookies
to true
in a client constructor if you would like to use a shared cookie jar for all requests.
// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$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)
.
$jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
[
'some_cookie' => 'foo',
'other_cookie' => 'barbaz1234'
],
'example.org'
);
You can get a cookie by its name with the getCookieByName($name)
method which returns a GuzzleHttp\Cookie\SetCookie
instance.
$cookie = $jar->getCookieByName('some_cookie');
$cookie->getValue(); // 'foo'
$cookie->getDomain(); // 'example.org'
$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.