PHP Cookies
Cookies store small amounts of data on the client's browser. Perfect for preferences, tracking, and "remember me" functionality!
Output
Click Run to execute your code
Setting a Cookie
<?php
// Basic cookie (expires in 1 hour)
setcookie("username", "john_doe", time() + 3600, "/");
// Cookie with all options
setcookie(
"user_pref", // name
"dark_mode", // value
time() + (86400 * 30), // expires in 30 days
"/", // path
"", // domain
false, // secure (HTTPS only)
true // httponly (not accessible via JS)
);
?>
Reading a Cookie
<?php
if (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'];
}
?>
Deleting a Cookie
<?php
// Set expiration to past
setcookie("username", "", time() - 3600, "/");
?>
Summary
- setcookie(): Must be before output
- $_COOKIE: Read cookie values
- httponly: Prevent JavaScript access
- secure: HTTPS only
- Don't store sensitive data
What's Next?
Finally, learn about File Uploads - handling user file submissions!
Enjoying these tutorials?