A Cookie is a small piece of data that a server sends to a user’s web browser. The browser stores it and sends it back to the server with subsequent requests. This allows the server to recognize the user and maintain session state.
Cookies are stored on the client-side (the user’s machine).
1. Creating a Cookie (setcookie())
To create a cookie, you use the setcookie() function. This function must be called before any HTML output (including blank lines or spaces) is sent to the browser, as it sends an HTTP header.
| Syntax | Description |
setcookie(name, value, expires, path, domain, secure, httponly) | Sends the cookie to the browser. |
| Parameter | Purpose | Example |
name (required) | The unique name of the cookie (e.g., "user_id"). | "theme" |
value (required) | The data to be stored (e.g., "dark"). | "dark" |
expires (optional) | The future timestamp when the cookie should expire. Must be a Unix timestamp. | time() + (86400 * 30) (30 days) |
path (optional) | The server path where the cookie will be available (e.g., "/" for the entire site). | "/" |
secure (optional) | If true, the cookie is only transmitted over HTTPS. | true |
httponly (optional) | If true, the cookie cannot be accessed via JavaScript. Highly recommended for security. | true |
Example: Setting a Preference Cookie
<?php
// Set a cookie named 'user_preference' with value 'compact'
// It will expire in 1 hour (3600 seconds)
$expiration_time = time() + 3600;
setcookie("user_preference", "compact", $expiration_time, "/", "", true, true);
?>
<!DOCTYPE html>
<html>
```
---
### 2. Retrieving Cookie Values (`$_COOKIE`)
Once a cookie is set, it is sent back to the server on every subsequent request and populated into the **`$_COOKIE`** superglobal array.
The cookie value is available on the **next page load**, not the page on which it was set.
**Example: Reading the Preference**
```php
<?php
if (isset($_COOKIE['user_preference'])) {
$preference = $_COOKIE['user_preference'];
echo "Welcome back! Your layout preference is: <strong>$preference</strong>";
// Use the preference to style the page
if ($preference == 'compact') {
echo '<style>body { font-size: 0.9em; }</style>';
}
} else {
echo "First time visitor. Defaulting to standard layout.";
}
?>
3. Deleting a Cookie
You cannot directly delete a cookie from the server. Instead, you instruct the browser to delete it by resetting its expiration time to a time in the past.
Important: The setcookie() function must be called with the same name and path as the original cookie.
Example: Logging Out (Deleting a User Session Cookie)
<?php
if (isset($_COOKIE['session_token'])) {
// Set the expiration time to an hour ago
$past_time = time() - 3600;
// Must use the same name and path as when it was created!
setcookie("session_token", "", $past_time, "/");
echo "Cookie 'session_token' deleted. You are now logged out.";
}
?>
4. Security Best Practices
Since cookies are stored on the client’s machine, they are vulnerable to inspection and tampering.
- Never Store Sensitive Data: Do not store passwords, credit card numbers, or other sensitive information directly in a cookie.
- Use
httponly = true: This prevents JavaScript from accessing the cookie, mitigating the risk of Cross-Site Scripting (XSS) attacks, where an attacker might try to steal cookies using injected code. - Use
secure = true: Ensure cookies containing tokens or sensitive session information are only sent over HTTPS (encrypted connections). - Only Store Tokens/IDs: Store only a non-sensitive token or user ID in the cookie, and use that token to look up the user’s secure details on the server (often via a database).
