Server Sessions Demo
How Server Sessions Work
Server sessions combine the best of both worlds: a small cookie holds just an ID, while all the actual data stays safely on the server.
Browser Server
| |
|---- POST /login ------------------>|
| username=alice, password=*** |
| | Validate credentials
| | session_start()
| | Generate ID: "abc123"
| | Create file: /tmp/sess_abc123
| | Write: {user_id: 1, username: "alice"}
|<--- Set-Cookie: PHPSESSID=abc123 --|
| |
|---- GET /dashboard --------------->|
| Cookie: PHPSESSID=abc123 |
| | session_start()
| | Read /tmp/sess_abc123
| | $_SESSION = {user_id: 1, username: "alice"}
|<--- "Welcome, Alice!" -------------|
Key insight: The browser only knows a random ID. All sensitive data (user info, permissions, cart contents) stays on the server where it can't be tampered with.
Why Sessions Over Plain Cookies?
| Plain Cookies |
Server Sessions |
| Data stored in browser |
Data stored on server |
| ~4KB size limit |
Unlimited size |
| User can view/modify data |
User sees only opaque ID |
| Sent with every request (slow) |
Only tiny ID sent |
| Client-side manipulation risk |
Server-controlled security |
Try the Demo
Go to Login Page
Demo credentials:
Username: admin
Password: secret
(Or use any username with password "password")
PHP Session Functions
<?php
// Start or resume a session (MUST be before any output)
session_start();
// Store data in session
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'alice';
$_SESSION['role'] = 'admin';
// Read session data
echo $_SESSION['username']; // 'alice'
// Check if key exists
if (isset($_SESSION['user_id'])) {
echo "User is logged in";
}
// Remove specific key
unset($_SESSION['temp_data']);
// Regenerate session ID (security - do this on login!)
session_regenerate_id(true);
// Destroy entire session (logout)
session_destroy();
?>
Session Security Best Practices
| Practice |
Why |
session_regenerate_id(true) on login |
Prevents session fixation attacks |
| Use HTTPS |
Prevents session ID interception |
Set httponly cookie flag |
Prevents JavaScript theft of session ID |
Set secure cookie flag |
Only send cookie over HTTPS |
| Validate user agent/IP (carefully) |
Detect session hijacking |
Demo Flow
- login.php - Shows login form, handles authentication
- dashboard.php - Protected page, requires session
- logout.php - Destroys session, clears cookie
Previous: Cookies |
Next: Client Storage