Lesson 10 โข Intermediate
Sessions & Cookies ๐ช
Persist data between page loads โ use sessions for secure server-side storage and cookies for client-side preferences.
What You'll Learn in This Lesson
- โข How sessions maintain state across HTTP requests
- โข Setting, reading, and destroying session variables
- โข Creating and deleting cookies with secure settings
- โข When to use sessions vs cookies
- โข Building a secure login system with "remember me"
Try It: PHP Sessions
Start sessions, store login data, check authentication status
// PHP Sessions (simulated in JavaScript)
console.log("=== How Sessions Work ===");
console.log();
console.log("HTTP is STATELESS โ each request is independent.");
console.log("Sessions let you remember users between page loads.");
console.log();
console.log("1. User visits site โ PHP generates session ID");
console.log("2. Session ID stored in browser cookie (PHPSESSID)");
console.log("3. Server stores data linked to that ID");
console.log("4. Next request โ browser sends cookie โ server finds
...Try It: Cookies & Security
Set secure cookies, compare sessions vs cookies, and build a login system
// PHP Cookies (simulated in JavaScript)
console.log("=== Sessions vs Cookies ===");
console.log();
console.log("Feature | Sessions | Cookies");
console.log("โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโ");
console.log("Stored on | Server | Client (browser)");
console.log("Security | More secure | Less secure");
console.log("Max size | No practical limit | 4KB per cookie");
console.log("Lifetime | Browser close* | Custom
...โ ๏ธ Common Mistakes
session_regenerate_id(true) after successful login to prevent session fixation attacks.httponly: true and secure: true on cookies to prevent JavaScript access and ensure HTTPS-only transmission.๐ Quick Reference โ Sessions & Cookies
| Function | Purpose |
|---|---|
| session_start() | Start/resume a session |
| $_SESSION['key'] | Get/set session data |
| session_destroy() | Destroy entire session |
| setcookie() | Create/update a cookie |
| $_COOKIE['name'] | Read a cookie value |
| session_regenerate_id() | Prevent session fixation |
๐ Lesson Complete!
You now understand state management in PHP! Next, level up with Object-Oriented Programming.
Sign up for free to track which lessons you've completed and get learning reminders.