Cookies are small pieces of data stored by a web browser. PHP can create, read, update, and delete cookies. They are often used for remembering preferences, language choices, and other non-sensitive information.
A cookie is stored in the visitor's browser and is sent back to the server with matching requests, subject to its domain, path, expiry, and security settings.
Cookies are different from PHP session data. A cookie is stored in the browser, while session data is generally stored on the server.
Important: Do not store passwords, payment details, or other sensitive information directly in ordinary cookies.
PHP provides the setcookie() function to
send a cookie to the browser.
<?php
setcookie("username", "Rahul", time() + 3600, "/");
echo "Cookie has been sent to the browser.";
?>
The cookie is requested to remain available for one hour.
The fourth argument, "/", makes it available
across paths on the same host.
Remember: Cookies must be sent before any HTML output or other response body content. If output has already started, PHP may report a headers already sent warning.
A successful call to setcookie() sends a
header; it does not immediately add the cookie to the
current request's $_COOKIE array.
PHP reads cookies sent by the browser through the
$_COOKIE superglobal.
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome, " . htmlspecialchars(
$_COOKIE["username"],
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
);
} else {
echo "Username cookie is not available.";
}
?>
Example output: Welcome, Rahul
To test this example, first create the cookie and then reload the page or open another request to the same path. The browser must accept and send the cookie.
Always treat cookie values as untrusted input. A user can change cookie values using browser developer tools.
The third argument of setcookie() specifies
the cookie's expiration timestamp.
<?php
setcookie("theme", "dark", time() + 86400, "/");
echo "Theme preference cookie has been sent.";
?>
86400 seconds equals 24 hours.
<?php
setcookie("visit_mode", "normal", 0, "/");
echo "A browser-session cookie has been sent.";
?>
An expiration value of 0 requests a
browser-session cookie, which normally expires when the
browser session ends. Browser behavior can vary.
Cookie expiration is not a guarantee that data will be erased at an exact moment. Browsers may remove cookies earlier.
To update a cookie, call setcookie() again
using the same cookie name and matching path and domain
settings.
<?php
setcookie("username", "Priya", time() + 3600, "/");
echo "Username cookie has been updated.";
?>
On the next request, if the browser accepts and sends the updated cookie, PHP can read the new value.
Important: The current request's
$_COOKIE["username"] still contains the
value sent by the browser at the beginning of that request.
The cookie name, path, and domain identify which cookie is being updated. If the path or domain differs, a separate cookie may be created instead.
To request deletion, send a cookie with an expiration time in the past. Use the same path and domain settings that were used when creating it.
<?php
setcookie("username", "", time() - 3600, "/");
echo "Cookie deletion has been requested.";
?>
The browser processes the deletion instruction from the
response. The cookie may still appear in the current
request's $_COOKIE array.
If you originally set options such as a specific path, domain, or partitioning setting, use matching options when deleting the cookie.
PHP allows you to configure cookie security options.
Use the options-array form of setcookie()
in modern PHP versions.
<?php
setcookie("theme", "dark", [
"expires" => time() + 86400,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax"
]);
echo "Cookie options have been configured.";
?>
expires sets the expiration timestamp.path controls the URL paths that receive the cookie.secure sends the cookie over HTTPS connections.httponly prevents normal JavaScript access to the cookie.samesite helps control cross-site cookie sending.
Use "secure" => true on an HTTPS website.
For local HTTP development, this setting may prevent the
browser from sending the cookie.
HttpOnly does not prevent every type of
attack, and SameSite is not a complete
replacement for appropriate CSRF protection.
This example remembers a user's theme preference.
Save it as theme.php to test it separately.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$theme = $_POST["theme"] ?? "";
if (in_array($theme, ["light", "dark"], true)) {
setcookie("theme", $theme, [
"expires" => time() + 86400 * 30,
"path" => "/",
"secure" => !empty($_SERVER["HTTPS"])
&& $_SERVER["HTTPS"] !== "off",
"httponly" => true,
"samesite" => "Lax"
]);
header("Location: theme.php");
exit;
}
}
$currentTheme = $_COOKIE["theme"] ?? "light";
if (!in_array($currentTheme, ["light", "dark"], true)) {
$currentTheme = "light";
}
$background = $currentTheme === "dark" ? "#222" : "#fff";
$foreground = $currentTheme === "dark" ? "#fff" : "#222";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Theme Preference</title>
</head>
<body style="background: <?= $background ?>;
color: <?= $foreground ?>;">
<h2>Remember My Theme</h2>
<p>Current theme: <?= htmlspecialchars(
$currentTheme,
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
) ?></p>
<form method="post">
<label for="theme">Choose theme:</label>
<select id="theme" name="theme">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<button type="submit">Save Preference</button>
</form>
</body>
</html>
The page redirects after saving the preference so the browser can send the updated cookie on the next request.
This example uses a simple allowlist for theme values. It does not store sensitive information in the cookie.
Cookies and sessions can both help a website remember information between requests, but they work differently.
| Feature | Cookies | Sessions |
|---|---|---|
| Storage | Browser | Usually server |
| Access | Sent with matching requests | Accessed through server-side session data |
| Lifetime | Session or configured expiry | Depends on session configuration and handling |
| Common uses | Theme and language preferences | Login state and temporary user data |
<?php
session_start();
$_SESSION["username"] = "Rahul";
echo "Session data has been saved.";
?>
Call session_start() before sending page
output. In a login system, use secure session settings,
regenerate the session ID after authentication, and
validate permissions on the server.
1. Which PHP function creates or updates a cookie?
2. Which superglobal reads cookies sent by the browser?
3. What does the HttpOnly cookie option do?