Cookies are small bits of data that a server stores directly in the user's browser. Unlike sessions where the data lives on the server, cookies live on the user's machine. That makes them useful for remembering things like language preferences, theme choices, or whether the user accepted your cookie notice.
Setting a Cookie with setcookie()
To set a cookie in PHP, use setcookie(). It needs at least a name and a value. You call it before any HTML output โ just like session_start(). The browser will then store that cookie and send it back with every subsequent request to your server.
<?php
setcookie("theme", "dark", time() + 86400);
setcookie("language", "en", time() + 86400);
echo "Cookies have been set!";
?>
Try it Yourself โ
Reading Cookies with $_COOKIE
When a browser sends cookies back to your server, PHP makes them available in the $_COOKIE superglobal. Check if a cookie exists before reading it, because trying to access a missing cookie will throw a notice.
<?php
if (isset($_COOKIE["theme"])) {
$theme = $_COOKIE["theme"];
echo "Your theme preference is: " . $theme;
} else {
echo "No theme preference set.";
}
?>
Try it Yourself โ
Cookie Parameters: Expiry, Path, and Domain
The setcookie() function has several parameters. The third one is expires โ a Unix timestamp telling the browser when to delete the cookie. Use time() + seconds to set it. You can also set a path (only send the cookie on certain pages) and a domain (restrict to a subdomain).
<?php
setcookie("remember_me", "1", time() + 2592000, "/");
?>
Try it Yourself โ
Cookies vs Sessions
Cookies store data on the user's browser. Sessions store data on the server. Cookies can persist for weeks or years. Sessions die when the browser closes (usually). Cookies are good for remembering preferences. Sessions are good for logins and sensitive data. In practice, you'll use both โ sessions for the important stuff, cookies for the small stuff.