Quick start guide
In this guide we will build the smallest useful cookie flow: read an incoming cookie, set it if it does not exist, and delete it again when we no longer need it.
1. Install the package
composer require phpgt/cookie
2. Create a CookieHandler
In plain PHP, construct the handler from $_COOKIE:
use GT\Cookie\CookieHandler;
$cookies = new CookieHandler($_COOKIE);
The constructor copies the current request cookies into Cookie objects. After construction, the handler is the object we pass around instead of the superglobal.
3. Read an existing cookie
We can check for a cookie before reading it:
if($cookies->contains("theme")) {
echo "Your saved theme is " . $cookies["theme"];
}
Array access is intentionally similar to $_COOKIE. If the cookie does not exist, $cookies["theme"] returns null.
4. Set a cookie
Use set() when we want the browser to store a cookie:
$cookies->set(
"theme",
"dark",
new DateTime("+1 year"),
secure: true,
httponly: true,
);
This updates the handler immediately and calls PHP’s setcookie() so the browser receives the Set-Cookie response header.
[!IMPORTANT] Cookies are sent as HTTP headers. In a plain PHP script, call
set()ordelete()before output has started, otherwise PHP may not be able to send the header.
5. Delete a cookie
When the cookie should no longer be used:
$cookies->delete("theme");
The cookie is removed from the handler, and the browser is sent an expired cookie with the same name.
6. Use the handler in application code
Once the handler exists, pass it to the part of the application that needs cookies:
function rememberTheme(CookieHandler $cookies, string $theme):void {
$cookies->set(
"theme",
$theme,
new DateTime("+1 year"),
secure: true,
httponly: true,
);
}
That keeps the rest of the code independent from $_COOKIE, which makes the function easier to test and easier to reuse.
Next, see Reading cookies for all of the ways to inspect the handler.