Guide for cookie and cookiejar manipulation

SERPS offers convenient tools that emulate a cookiejar and allow to persist cookies across many requests.

The following examples introduce the work with cookies


Cookies usage is still at prototype stage and all http engines do not support cookies yet.

Parameters for creating a cookie:

use Serps\Core\Cookie\Cookie;

$cookie = new Cookie('baz', 'bar', [
    'domain' => '',
    'path' => '/',
    'expires' => time() + 1000,
use Serps\Core\Cookie\ArrayCookieJar;

$cookieJar = new ArrayCookieJar();

// Add the cookie 'foo' with value 'bar' for the domain ''
$cookie = new Cookie('foo', 'bar', ['domain' => '']);

// Add the cookie 'baz' with value 'bar' for the domain ''
$cookie = new Cookie('baz', 'bar', ['domain' => '']);

Retrieving cookies

The all method is responsible for getting cookies matching some filters

Method parameters:

// Retrieves all cookies
$cookies = $cookieJar->all();

// Retrieves all cookies matching the domain ""
$cookies = $cookieJar->all("");

// Retrieves the cookie named "foo" for the domain "", including expired cookies
$cookies = $cookieJar->all("", "/", "foo", false, false);

Retrieve cookies for a request

It's possible to automatically retrieve cookies that match a given PSR-7 request:

// retrieves all cookies matching the request
$cookies = $cookieJar->getMatchingCookies($request);

Remove cookies

// Remove all cookies
$cookies = $cookieJar->remove();

// Remove all cookies matching the domain ""
$cookies = $cookieJar->remove("");

// Remove the cookie named "foo" for the domain ""
$cookies = $cookieJar->remove("", "/", "foo");

Remove temporary cookies

// Remove all temporary cookies
$cookies = $cookieJar->removeTemporary();

Remove expired cookies

// Remove all cookies that are expired
$cookies = $cookieJar->removeExpired();

Serialize cookies

Cookies can be exported in a serializable format, thus it's possible to save the state and to use it latter.

// serialize cookies using json
$serializableCookieJar = $cookieJar->export();
$serializedCookieJar = json_encode($serializableCookieJar);

// Unserialize cookies in an other cookie jar
$otherCookieJar->import(json_decode($serializedCookieJar, true));