Skip to content
Greg Bowler edited this page Apr 23, 2026 · 3 revisions

phpgt/cookie gives us an object oriented way to work with HTTP cookies without reading from and writing to the $_COOKIE superglobal throughout our application.

Cookies are small pieces of text sent by the browser with each request. They are useful for remembering lightweight client-side state, such as a preference, a tracking token, or the identifier used by a server-side session system.

Native PHP exposes incoming cookies through $_COOKIE, and sends outgoing cookies with the global setcookie() function. This library keeps that same browser behaviour, but wraps the cookie data in a small API that is easier to pass around, test, and understand where data is being changed.

Note

WebEngine depends on this package as one of its small single-purpose components. In a WebEngine application, global variables are protected by default, so cookie access should be handled explicitly rather than by reaching into $_COOKIE throughout page logic.

What this library covers

  • Creating a CookieHandler from the current request cookies.
  • Reading cookies using method calls or array-style syntax.
  • Checking whether a cookie exists.
  • Setting cookies by calling PHP's setcookie() behind the scenes.
  • Deleting one cookie, several cookies, or every tracked cookie.
  • Iterating over cookies and exporting them as a plain array.
  • Representing individual cookies as immutable Cookie objects.
  • Validating cookie names and values before they are accepted.

A small example

use GT\Cookie\CookieHandler;

$cookies = new CookieHandler($_COOKIE);

if(!$cookies->contains("firstVisit")) {
	$cookies->set(
		"firstVisit",
		date("c"),
		new DateTime("+30 days"),
		secure: true,
		httponly: true,
	);
}

echo $cookies["firstVisit"] ?? "Welcome!";

The CookieHandler lets us read cookies with the same familiar ["name"] syntax as $_COOKIE, while still giving us explicit methods for operations that affect the browser response.


To start from the smallest working example, continue with the Quick start guide.

Clone this wiki locally