Skip to content

API reference

Greg Bowler edited this page Apr 23, 2026 · 1 revision

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): bool
  • get(string $name): ?Cookie
  • asArray(): array
  • count(): int

asArray() returns array<string, string>.

Writing methods

  • set(string $name, string $value, ?DateTimeInterface $expires = null, string $domain = "", bool $secure = false, bool $httponly = false): void
  • delete(string $name): void
  • clear(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] = $value throws CookieSetException.

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(): string
  • getName(): string
  • getValue(): string
  • withValue(string $value): self

withValue() returns a cloned Cookie with the new value.

Validity

Validity exposes the character validation used by Cookie.

  • Validity::getValidNameCharacters(): array
  • Validity::getValidValueCharacters(): array
  • Validity::isValidName(string $name): bool
  • Validity::isValidValue(string $value): bool

Exceptions

  • CookieException
  • CookieSetException
  • InvalidCharactersException

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.

Clone this wiki locally