Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

4. State Management

Lesson 18 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

State Management in PHP: Concepts, Techniques & Comparison

Study Deep: Session Hijacking vs. Session Fixation

Understanding session security is vital for any advanced PHP student.

  1. 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 validate User-Agent.
  1. 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:

FunctionPurpose
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:

FunctionPurpose
session_start()Starts or resumes a session (MUST be first line of script)
$_SESSION['key'] = valueStores 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

FeatureCookiesSessionsURL RewritingHidden Fields
Storage LocationClient BrowserServerURLHTML Form
Security LevelLow (user can edit)High (data on server)Low (visible to all)Low (viewable in page source)
Data Capacity~4KBUnlimitedLimited by URL lengthUnlimited
ExpiresSet by developerBrowser close (or manual)Immediate (per-request)On form submit only
Persistent?Yes (until expiry)No (session ends on close)NoNo
Requires Cookie?NoYes (for session ID)NoNo
Best Use CaseRemember Me, PreferencesUser login, Shopping cartPagination, Record IDsMulti-step forms, CSRF tokens