PHP Cookies
Cookies are small text files stored on the client's browser. PHP uses setcookie() to create them and $_COOKIE to read them. Cookies must be set before any HTML output.
Setting and Reading Cookies
The setcookie() function accepts: name, value, expiry, path, domain, secure, and httponly parameters.
<?php
// setcookie(name, value, expire, path, domain, secure, httponly)
// Simple cookie — expires in 1 hour
setcookie("username", "Alice", time() + 3600);
// Cookie with all parameters
setcookie(
"theme", // name
"dark", // value
time() + 86400*30, // expire: 30 days
"/", // path: entire site
"", // domain: current domain
true, // secure: HTTPS only
true // httponly: no JS access
);
// Session cookie (expires when browser closes)
setcookie("temp_token", "abc123");
// Read cookies on next request
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . htmlspecialchars($_COOKIE["username"]);
} else {
echo "No cookie found";
}
?>
Modifying and Deleting Cookies
To modify a cookie, call setcookie() again with the same name and a new value. To delete it, set the expiry to a time in the past.
<?php
// Modify — overwrite with new value and new expiry
setcookie("username", "Bob", time() + 3600);
// Delete — set expiry in the past
setcookie("username", "", time() - 3600);
// Also unset from current request's $_COOKIE
unset($_COOKIE["username"]);
// Check all cookies
foreach ($_COOKIE as $name => $value) {
echo htmlspecialchars($name) . " = " . htmlspecialchars($value) . "\n";
}
// Practical: remember user preference
if (!isset($_COOKIE["lang"])) {
setcookie("lang", "en", time() + 86400 * 365, "/");
}
$lang = $_COOKIE["lang"] ?? "en";
echo "Language: $lang";
?>
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.