PHP.GT

Reading cookies

CookieHandler is designed to feel familiar if we have used $_COOKIE, while still being explicit about the difference between reading cookies and sending new cookie headers.

Constructing from request cookies

The most common starting point is the current request:

use GT\Cookie\CookieHandler;

$cookies = new CookieHandler($_COOKIE);

The array keys become cookie names, and the array values become cookie values. Each entry is stored internally as a Cookie object.

For tests or command-line scripts, we can pass any array<string, string>:

$cookies = new CookieHandler([
	"theme" => "dark",
	"currency" => "GBP",
]);

Checking for a cookie

Use contains() when the code needs to know whether the cookie exists:

if($cookies->contains("currency")) {
	echo "Currency preference found";
}

This is equivalent to using isset() with array access:

if(isset($cookies["currency"])) {
	echo "Currency preference found";
}

Reading a value

Array access returns the cookie value as a string:

$currency = $cookies["currency"];

If the cookie does not exist, array access returns null:

$currency = $cookies["currency"] ?? "GBP";

Reading the Cookie object

When we need the name and value together, use get():

$cookie = $cookies->get("currency");

if($cookie) {
	echo $cookie->getName() . " = " . $cookie->getValue();
}

get() returns null when the cookie does not exist.

Iterating over cookies

CookieHandler is iterable. The key is the cookie name, and the value is the cookie value:

foreach($cookies as $name => $value) {
	echo "$name = $value\n";
}

The handler is also countable:

echo "There are " . count($cookies) . " cookies in this request.";

Exporting as an array

Use asArray() when another API needs plain cookie data:

$cookieArray = $cookies->asArray();

The returned array has the same basic shape as $_COOKIE: names as keys, values as strings.


Next, see Setting and deleting cookies for the methods that send Set-Cookie headers.