-
-
Notifications
You must be signed in to change notification settings - Fork 0
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.
composer require phpgt/cookieIn 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.
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.
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() or delete() before output has started, otherwise PHP may not be able to send the header.
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.
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.
PHP.GT/Cookie is a separately maintained component of PHP.GT/WebEngine.