-
-
Notifications
You must be signed in to change notification settings - Fork 0
Examples
These examples show the library on its own. In a larger application, the same operations usually live inside controllers, page logic functions, or small services.
use GT\Cookie\CookieHandler;
$cookies = new CookieHandler($_COOKIE);
if($_SERVER["REQUEST_METHOD"] === "POST") {
$scheme = $_POST["scheme"] ?? "light";
$cookies->set(
"colourScheme",
$scheme,
new DateTime("+6 months"),
secure: true,
httponly: true,
);
}
$currentScheme = $cookies["colourScheme"] ?? "light";The preference is available immediately from the handler after set() is called, and it will be sent back by the browser on later requests if the browser accepts the cookie.
use GT\Cookie\CookieHandler;
$cookies = new CookieHandler($_COOKIE);
if(isset($_POST["dismiss-intro"])) {
$cookies->set(
"dismissedIntro",
"1",
new DateTime("+1 year"),
secure: true,
httponly: true,
);
}
if(!$cookies->contains("dismissedIntro")) {
echo "<p>Welcome to the application.</p>";
}This is a good use for a cookie because the value is small and does not need to be private.
use GT\Cookie\CookieHandler;
$cookies = new CookieHandler($_COOKIE);
$cookies->clear(
"colourScheme",
"dismissedIntro",
"currency",
);Use this for "reset preferences" features, where a small known group of cookies should be removed together.
use GT\Cookie\CookieHandler;
function getCurrency(CookieHandler $cookies):string {
return $cookies["currency"] ?? "GBP";
}
function rememberCurrency(CookieHandler $cookies, string $currency):void {
$cookies->set(
"currency",
$currency,
new DateTime("+1 year"),
secure: true,
httponly: true,
);
}Passing the handler in makes the dependency clear. The function can be tested with a simple in-memory handler:
$cookies = new CookieHandler([
"currency" => "EUR",
]);
assert(getCurrency($cookies) === "EUR");use GT\Cookie\Cookie;
$cookie = new Cookie("currency", "GBP");
$updated = $cookie->withValue("EUR");
echo $cookie->getValue(); // GBP
echo $updated->getValue(); // EURThis is useful when a function should work with one cookie value without needing the whole handler.
For the complete method list, see the API reference.
PHP.GT/Cookie is a separately maintained component of PHP.GT/WebEngine.