State Management in PHP: Concepts, Techniques & Comparison
Study Deep: Session Hijacking vs. Session Fixation
Understanding session security is vital for any advanced PHP student.
- Session Hijacking: When an attacker steals a user's session ID (usually via XSS or sniffing) and uses it to impersonate them.
- Defense: Use HTTPS, set
session.cookie_httponly = 1, and validateUser-Agent.
- Session Fixation: When an attacker forces a specific session ID on a user (e.g., via a link) and then waits for them to log in.
- Defense: Always use
session_regenerate_id(true)immediately after a user successfully logs in.
1. What is State Management?
Definition: State Management is the practice of maintaining the state (current condition or data) of a user's interaction with a web application across multiple HTTP requests and page loads.
The Core Problem — HTTP is Stateless: HTTP (HyperText Transfer Protocol) is a stateless protocol. This means:
- Each HTTP request is treated as a completely independent transaction.
- After the server sends a response, it immediately forgets everything about that interaction.
- The server has no built-in memory of who the user is, what they last did, or whether they are logged in.
Real-World Consequences: Without state management:
- A user logs in, but the next page cannot tell they are logged in.
- A shopping cart loses its contents every time you navigate to a new page.
- A multi-step form cannot remember Step 1 answers when you're on Step 2.
Solution: State Management techniques allow us to persist data across requests.
2. Technique 1: Cookies
Definition: A Cookie is a small text file that the server instructs the browser to store on the client's computer. The browser automatically sends the cookie data back to the server with every subsequent request to the same domain.
Key Properties:
- Storage Location: Client-side (user's browser)
- Size Limit: ~4KB per cookie
- Expiry: Developer-defined using a Unix timestamp
- Security: Low — users can view and edit cookies in browser dev tools
PHP Functions for Cookies:
| Function | Purpose |
|---|---|
setcookie(name, value, expire, path) | Creates a cookie on the client |
$_COOKIE['name'] | Reads a cookie value |
setcookie('name', '', time()-1) | Deletes a cookie (set past expiry) |
// Setting a cookie (expires in 30 days)
setcookie("username", "Rohit", time() + (86400 * 30), "/");
// Reading a cookie
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"] . "!";
} else {
echo "Please log in.";
}
// Deleting a cookie
setcookie("username", "", time() - 3600, "/");
3. Technique 2: Sessions
Definition: A Session stores user information on the server side. When a session is started, PHP creates a unique Session ID (a long random string), stores it in a cookie on the client, and links it to session data stored in a file on the server.
Key Properties:
- Storage Location: Server-side (session data in temp files)
- Size Limit: No practical limit
- Expiry: When the browser is closed (by default), or via
session_destroy() - Security: Higher than cookies — the actual data never leaves the server
PHP Functions for Sessions:
| Function | Purpose |
|---|---|
session_start() | Starts or resumes a session (MUST be first line of script) |
$_SESSION['key'] = value | Stores a value in the session |
$_SESSION['key'] | Reads a session value |
unset($_SESSION['key']) | Removes a specific session variable |
session_destroy() | Destroys the entire session (logout) |
<?php
session_start(); // Must be called before any output
// Store session data
$_SESSION["user"] = "Rohit";
$_SESSION["role"] = "Admin";
// Read session data
echo "Logged in as: " . $_SESSION["user"];
// Logout: destroy session
session_unset(); // Clear all session variables
session_destroy(); // Destroy the session file on server
?>
4. Technique 3: URL Rewriting (Query Strings)
Definition: Appending data directly to the end of a URL as a query string, in the format page.php?key=value&key2=value2.
When to use: Best for non-sensitive data like record IDs, page numbers, or search filters that need to be shareable via a link.
<!-- Creating the link with data -->
<a href="profile.php?id=101&lang=en">View Profile</a>
<?php
// Reading the query string in profile.php
$userId = $_GET['id'];
$lang = $_GET['lang'];
echo "Loading profile for user ID: $userId in language: $lang";
?>
5. Technique 4: Hidden Form Fields
Definition: Invisible <input type="hidden"> elements embedded in HTML forms. When the form is submitted, these hidden values are sent along with the visible form data.
When to use: Passing data between steps of a multi-page form (wizard), or carrying over context data between pages where links aren't used.
<!-- Page 1: Visible form with hidden transaction ID -->
<form method="POST" action="step2.php">
<input type="hidden" name="step" value="1">
<input type="hidden" name="csrf_token" value="abc123xyz">
Your Name: <input type="text" name="name">
<input type="submit" value="Next Step">
</form>
<?php // step2.php
$name = $_POST['name'];
$step = $_POST['step'];
$token = $_POST['csrf_token'];
echo "Name from step $step: $name";
?>
6. Complete Comparison of All State Management Techniques
| Feature | Cookies | Sessions | URL Rewriting | Hidden Fields |
|---|---|---|---|---|
| Storage Location | Client Browser | Server | URL | HTML Form |
| Security Level | Low (user can edit) | High (data on server) | Low (visible to all) | Low (viewable in page source) |
| Data Capacity | ~4KB | Unlimited | Limited by URL length | Unlimited |
| Expires | Set by developer | Browser close (or manual) | Immediate (per-request) | On form submit only |
| Persistent? | Yes (until expiry) | No (session ends on close) | No | No |
| Requires Cookie? | No | Yes (for session ID) | No | No |
| Best Use Case | Remember Me, Preferences | User login, Shopping cart | Pagination, Record IDs | Multi-step forms, CSRF tokens |