🍪 PHP Cookie Management: Your Browser’s Memory Box
The Cookie Jar Analogy
Imagine your browser has a special memory box (like a cookie jar at grandma’s house). Every time you visit a website, the website can put a little note in your box. Next time you visit, it reads the note and remembers you!
That’s exactly what cookies are — tiny notes websites store in your browser to remember things about you.
🎯 What You’ll Learn
graph TD A["🍪 Cookie Management"] --> B["Setting Cookies"] A --> C["Reading Cookies"] A --> D["Deleting Cookies"] A --> E["Cookie Options"] B --> B1["Give browser a note"] C --> C1["Read the note back"] D --> D1["Throw away the note"] E --> E1["Special instructions"]
1️⃣ Setting Cookies — Giving Your Browser a Note
What Is It?
When you set a cookie, you’re telling the browser: “Hey, remember this for me!”
It’s like writing a note and putting it in a jar. The note has:
- A name (what to call it)
- A value (what to remember)
The Magic Words
setcookie("username", "Alex");
Translation: “Dear Browser, please remember that username is Alex.”
Real Example
<?php
// When user logs in
setcookie("username", "Alex");
setcookie("theme", "dark");
setcookie("language", "english");
?>
This creates 3 notes in the browser’s memory box:
- 📝 Note 1: username = Alex
- 📝 Note 2: theme = dark
- 📝 Note 3: language = english
⚠️ Super Important Rule!
Cookies must be set BEFORE any HTML output!
<?php
// ✅ CORRECT - Cookie first!
setcookie("name", "value");
?>
<html>...
<?php
// ❌ WRONG - HTML came first!
echo "Hello";
setcookie("name", "value"); // Error!
?>
Think of it like: You must put the note in the jar BEFORE opening the door to greet visitors.
2️⃣ Reading Cookies — Checking Your Notes
What Is It?
Reading cookies means looking at the notes you stored earlier. PHP uses a special box called $_COOKIE where all notes live.
The Magic Words
$value = $_COOKIE["username"];
Translation: “What did I write on the note named username?”
Real Example
<?php
// Check if the note exists first!
if (isset($_COOKIE["username"])) {
$user = $_COOKIE["username"];
echo "Welcome back, $user!";
} else {
echo "Hello, stranger!";
}
?>
Why Check First?
Imagine reaching into an empty jar — ouch! Always check if the note exists using isset() before reading.
<?php
// Reading multiple cookies
$theme = $_COOKIE["theme"] ?? "light";
$lang = $_COOKIE["language"] ?? "en";
echo "Theme: $theme";
echo "Language: $lang";
?>
The ?? means: “Use this value if the note doesn’t exist.”
3️⃣ Deleting Cookies — Throwing Away Notes
What Is It?
Sometimes you want to forget things (like when a user logs out). Deleting a cookie removes the note from the browser’s jar.
The Magic Trick
Set the cookie’s expiration to the PAST!
setcookie("username", "", time() - 3600);
Translation: “This note expired an hour ago. Throw it away!”
Real Example — Logout
<?php
// User clicks "Logout"
// Delete all their notes!
setcookie("username", "", time() - 3600);
setcookie("theme", "", time() - 3600);
setcookie("remember_me", "", time() - 3600);
echo "You've been logged out!";
?>
Visual Timeline
graph LR A["Now"] --> B["1 hour ago"] B --> C["Cookie expires here"] C --> D["🗑️ Deleted!"]
4️⃣ Cookie Options — Special Instructions
What Are Options?
When you put a note in the jar, you can add special instructions:
- ⏰ How long to keep it?
- 📁 Which pages can read it?
- 🔒 Is it secret?
- 🌐 Can it travel on the internet safely?
The Full Recipe
setcookie(
name, // Note name
value, // What to remember
expires, // When to throw away
path, // Which folders can see it
domain, // Which website owns it
secure, // HTTPS only?
httponly // Hide from JavaScript?
);
Option 1: Expiration Time ⏰
<?php
// Keep for 30 days
$thirtyDays = time() + (30 * 24 * 60 * 60);
setcookie("remember_me", "yes", $thirtyDays);
// Keep for 1 hour
$oneHour = time() + 3600;
setcookie("temp_data", "xyz", $oneHour);
// Delete when browser closes (no time set)
setcookie("session_id", "abc123");
?>
Option 2: Path 📁
Controls which pages can read the cookie.
<?php
// Only /admin pages can read this
setcookie("admin_token", "secret", 0, "/admin");
// All pages can read this (default)
setcookie("theme", "dark", 0, "/");
?>
Think of it like: Some notes are only for certain rooms in the house.
Option 3: Domain 🌐
Which website owns this cookie?
<?php
// Only this exact site
setcookie("data", "value", 0, "/", "mysite.com");
// Include all subdomains
setcookie("data", "value", 0, "/", ".mysite.com");
?>
Option 4: Secure 🔒
Only send cookie over HTTPS (encrypted connection).
<?php
// Only works on https:// websites
setcookie("secret", "value", 0, "/", "", true);
?>
Think of it like: This note can only travel in an armored truck, not a regular car.
Option 5: HttpOnly 🛡️
Hide cookie from JavaScript (extra security!).
<?php
// JavaScript cannot read this cookie
setcookie(
"session_id",
"abc123",
0,
"/",
"",
true, // secure
true // httponly
);
?>
This protects against hackers who try to steal cookies with malicious JavaScript.
🆕 Modern Way: The Options Array (PHP 7.3+)
The new, cleaner way to set all options:
<?php
setcookie("user_token", "xyz789", [
"expires" => time() + 86400,
"path" => "/",
"domain" => ".mysite.com",
"secure" => true,
"httponly" => true,
"samesite" => "Strict"
]);
?>
What’s SameSite?
Extra protection against sneaky attacks:
Strict— Cookie only sent from your siteLax— Sent when clicking links to your siteNone— Sent everywhere (needssecure)
🎯 Complete Example: Remember Me Login
<?php
// When user logs in with "Remember Me"
if ($loginSuccess && $rememberMe) {
setcookie("user_id", $userId, [
"expires" => time() + 2592000,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax"
]);
}
// On any page - check if remembered
if (isset($_COOKIE["user_id"])) {
$userId = $_COOKIE["user_id"];
// Auto-login the user!
}
// When logging out
setcookie("user_id", "", time() - 3600);
?>
📝 Quick Summary
| Action | Code | What It Does |
|---|---|---|
| Set | setcookie("name", "value") |
Creates a note |
| Read | $_COOKIE["name"] |
Reads the note |
| Delete | setcookie("name", "", time()-3600) |
Throws away note |
| With Options | setcookie("name", "val", [...]) |
Special instructions |
🌟 Remember These Golden Rules
- Set cookies BEFORE any output — Before
echo, before<html> - Always check if cookie exists — Use
isset()or?? - Delete by setting past expiration —
time() - 3600 - Use
httponlyfor security — Protect from JavaScript attacks - Use
securefor sensitive data — HTTPS only
🎉 You Did It!
You now understand PHP cookies! They’re just notes your website asks browsers to remember. You can:
- ✅ Create notes (set cookies)
- ✅ Read notes (access cookies)
- ✅ Throw away notes (delete cookies)
- ✅ Add special rules (cookie options)
Go build something amazing with your new cookie knowledge! 🚀
