Web Technology IIUnit 66 min read
Cookies, Sessions, Security: PHP Authentication & Data Persistence
Unit 6 of Web Technology II explores how PHP maintains user state via cookies and sessions, implements secure authentication, and defends against common attacks like session hijacking and XSS—with real-world examples from eSewa’s login system and Daraz’s cart persistence.
Core Concepts: Cookies vs. Sessions
What Are Cookies?
Cookies are small text files stored in the user’s browser. They persist after the browser closes unless explicitly deleted. PHP can read/write cookies using setcookie() and $_COOKIE.
stateDiagram-v2
[*] --> User: Opens Browser
User --> Server: Requests Page
Server --> User: Sets Cookie (e.g., `setcookie("user_id", "123", time()+3600)`)
User --> Server: Subsequent Requests
Server --> User: Reads Cookie via `$_COOKIE["user_id"]`Real-world use: eSewa stores your login status in a cookie to auto-fill your phone number on return visits.
What Are Sessions?
Sessions store data server-side (e.g., in files or databases) and use a session ID (stored in a cookie) to link requests to the same user. PHP manages sessions via session_start().
stateDiagram-v2
[*] --> User: Opens Browser
User --> Server: Requests Page
Server --> User: Starts Session (`session_start()`)
Server --> User: Generates Session ID (e.g., `abc123`)
Server --> User: Sets Cookie (`PHPSESSID=abc123`)
User --> Server: Subsequent Requests
Server --> User: Reads Session Data (`$_SESSION["cart"]`)Real-world use: Daraz uses sessions to keep your shopping cart alive even if you close the browser.
How They Work: Step-by-Step
1. Setting a Cookie
// Set a cookie lasting 1 hour
setcookie("username", "john_doe", time() + 3600, "/");
- Path:
/makes it available site-wide. - Expiry:
time() + 3600= 1 hour from now.
2. Reading a Cookie
if (isset($_COOKIE["username"])) {
echo "Welcome, " . $_COOKIE["username"];
}
3. Starting a Session
session_start(); // Must be called before output!
$_SESSION["user_id"] = 123;
- Session ID: Automatically stored in
PHPSESSIDcookie. - Storage: Defaults to
/tmpon Linux; configuresession.save_pathinphp.ini.
4. Destroying a Session
session_start();
session_unset(); // Clear all session data
session_destroy(); // Delete session file
Security Risks and Mitigations
Common Attacks
| Attack | Description | PHP Mitigation |
|---|---|---|
| Session Hijacking | Stealing PHPSESSID cookie |
Use session_regenerate_id(true) |
| XSS (Cross-Site Scripting) | Injecting malicious scripts | Sanitize output with htmlspecialchars() |
| CSRF (Cross-Site Request Forgery) | Tricking users into submitting forms | Use tokens: <input type="hidden" name="csrf_token" value="..."> |
Real-world example: Ncell’s login system uses HTTPS + session regeneration to prevent hijacking.
Secure Practices
- Always use
session_regenerate_id(true)after login to change the session ID. - Set
session.cookie_httponly = trueinphp.inito prevent JavaScript access. - Validate all user input before storing in sessions/cookies:
if (!preg_match("/^[a-zA-Z0-9_]+$/", $_POST["username"])) { die("Invalid username!"); }
Worked Example: Login System with Sessions
Scenario: A user logs into a bank’s website (e.g., NMB Bank). The system:
- Validates credentials.
- Starts a session.
- Redirects to dashboard.
// login.php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$password = $_POST["password"];
if (authenticate($username, $password)) {
$_SESSION["user_id"] = get_user_id($username);
$_SESSION["logged_in"] = true;
session_regenerate_id(true); // Prevent hijacking
header("Location: dashboard.php");
exit();
}
}
Real-world tie-in: NMB Bank’s login uses this exact flow, with additional 2FA for security.
Cookies vs. Sessions: Comparison
| Feature | Cookies | Sessions |
|---|---|---|
| Storage | Client-side (browser) | Server-side (file/database) |
| Security | Vulnerable to XSS/CSRF | More secure (ID can be regenerated) |
| Size Limit | ~4KB per cookie | No strict limit (depends on server) |
| Persistence | Can be disabled (e.g., incognito) | Persists until session_destroy() |
| Use Case | Tracking preferences (e.g., theme) | User authentication (e.g., eSewa login) |
Real-World Applications
1. eSewa’s Login System
- Idea Used: Sessions + HTTPS
- How: After entering your phone number and password, eSewa:
- Validates credentials.
- Starts a session with
session_regenerate_id(true). - Stores
user_idandbalancein$_SESSION. - Uses HTTPS to encrypt the
PHPSESSIDcookie.
- Why: Prevents session hijacking during transactions.
2. Daraz’s Shopping Cart
- Idea Used: Sessions for persistence
- How: Even if you close Daraz and return later, your cart items remain because:
- The session ID (
PHPSESSID) is stored in a cookie. - Daraz’s server reads
$_SESSION["cart"]on each visit.
- The session ID (
- Why: Cookies alone would fail if the user clears them.
3. NTC’s User Preferences
- Idea Used: Cookies for non-sensitive data
- How: NTC’s website remembers your language preference via a cookie:
setcookie("language", "ne", time() + 86400); // Nepali for 1 day - Why: Cookies are lightweight for non-critical data.
Exam Tip
- Diagrams: Draw a sequence diagram for login flow (browser → server → session creation).
- Code Snippets: Memorize:
setcookie()syntax.session_start()placement (before output!).session_regenerate_id(true)for security.
- Attacks: Know how to prevent session hijacking (regenerate ID) and XSS (sanitize output).
- Real Scenarios: Expect questions like:
- "How would you implement a ‘Remember Me’ feature for eSewa?" (Use long-lived cookies + encrypted tokens.)
- "Why is session storage safer than cookies for user IDs?" (Answer: server-side control, regeneration.)
Based on the TU BIM syllabus for Web Technology II (IT239), unit 6.
Discussion
Loading…