API reference
This page is a compact reference for the public API of the library.
For walkthroughs and examples, use the earlier pages in the guide.
CookieHandler
CookieHandler represents the collection of cookies for a request and response.
use GT\Cookie\CookieHandler;
$cookies = new CookieHandler($_COOKIE);
Constructor
__construct(array $existingCookies = [])
The array should be shaped like array<string, string>.
Reading methods
contains(string $name): boolget(string $name): ?CookieasArray(): arraycount(): int
asArray() returns array<string, string>.
Writing methods
set(string $name, string $value, ?DateTimeInterface $expires = null, string $domain = "", bool $secure = false, bool $httponly = false): voiddelete(string $name): voidclear(string ...$nameList): void
set() always sends the path / to PHP’s setcookie() function.
delete() expires the named cookie and removes it from the handler.
clear() with names clears only those cookies. clear() without names clears every cookie currently tracked by the handler.
ArrayAccess
isset($cookies[$name])checks whether the cookie exists.$cookies[$name]returns the cookie value as?string.unset($cookies[$name])deletes the cookie.$cookies[$name] = $valuethrowsCookieSetException.
Array assignment is not supported because setting a browser cookie needs expiry and security options.
Iterator
CookieHandler can be used in a foreach loop:
foreach($cookies as $name => $value) {
echo "$name: $value";
}
The key is the cookie name. The value is the cookie value.
Cookie
Cookie is an immutable value object.
Constructor
__construct(string $name, string $value = "")
Methods
__toString(): stringgetName(): stringgetValue(): stringwithValue(string $value): self
withValue() returns a cloned Cookie with the new value.
Validity
Validity exposes the character validation used by Cookie.
Validity::getValidNameCharacters(): arrayValidity::getValidValueCharacters(): arrayValidity::isValidName(string $name): boolValidity::isValidValue(string $value): bool
Exceptions
CookieExceptionCookieSetExceptionInvalidCharactersException
CookieSetException and InvalidCharactersException both extend CookieException.
Namespace
New code should use the GT\Cookie namespace:
use GT\Cookie\CookieHandler;
The package also keeps a Composer autoload mapping for the legacy Gt\Cookie prefix so older applications can continue to load the same classes.