PHP Cookies
intermediatePart of PHP Web Features
Theory
Cookies are small text files stored on the user's browser. PHP makes it easy to set, read, and manage cookies.
Setting Cookies with setcookie()
setcookie() must be called before any HTML output:
setcookie(
"username", // Name
"Alice", // Value
time() + 86400, // Expiration (1 day from now)
"/", // Path (available site-wide)
"", // Domain
true, // Secure (HTTPS only)
true // HttpOnly (not accessible by JavaScript)
);Reading Cookies
PHP automatically populates the $_COOKIE superglobal:
if (isset($_COOKIE['username'])) {
$user = $_COOKIE['username'];
echo "Welcome back, $user!";
} else {
echo "Welcome, new visitor!";
}Cookie Parameters
- Name — the cookie identifier
- Value — the data stored (should be encoded/encrypted for sensitive data)
- Expiration — Unix timestamp when the cookie expires
- Path — URL path where the cookie is available (
/= entire site) - Domain — which domain can access the cookie
- Secure — only send over HTTPS
- HttpOnly — prevent JavaScript access (XSS protection)
- SameSite — controls cross-site request behavior (
Lax,Strict,None)
Deleting Cookies
Set the expiration to a past time:
setcookie("username", "", time() - 3600, "/");Sessions vs Cookies
| Feature | Sessions | Cookies | |---------|----------|---------| | Storage | Server | Browser | | Size limit | Unlimited | ~4KB per cookie | | Security | Higher (data not exposed) | Lower (stored on client) | | Persistence | Until session ends | Configurable | | Performance | Server memory/disk | No server storage |
Cookie Management Example
phpPractical Examples
Example: Persistent User Preferences
phpExercises
Visitor Counter with Cookies
Create a PHP page that uses a cookie to track how many times a user has visited the page. Display the count and the time of their first visit.
Expected Output:
Visit #5. First visit: 2026-01-15 10:30:00