State management: cookies, sessions & hidden fields
HTTP forgets every client between requests, so dynamic sites must carry state themselves — in the browser (cookies, hidden fields, query strings, ViewState, Web Storage) or on the server (sessions, application state, databases). Sessions, cookie flags and session attacks are core exam material.
Medium 45 minSyllabus: “Dynamic web pages using database, forms and session”
Mark as
The idea in one minute
Picture a busy government office where the clerk has no memory at all. To carry on yesterday's work you can either bring all your papers every time (client-side state: cookies, hidden fields) or collect a token number at the first visit while the office keeps your file in a cabinet (server-side state: a session). The token is small and useless to others — unless someone steals or copies it, which is exactly what session attacks try to do.
Key points — the night-before list
HTTP is stateless: each request is independent, so login, carts and multi-step forms need state management.
Client-side: cookies (~4 KB, sent automatically), hidden form fields, URL rewriting / query strings, ViewState (ASP.NET), Web Storage (JavaScript only). The user can read and change all of them.
Server-side: session (one user), application state (all users), cache, database. Only an identifier travels to the browser.
A session works as: random session id → Set-Cookie → browser returns it on every request → server looks up the stored data → timeout or logout destroys it.
Session cookie = no Expires/Max-Age, gone when the browser closes; persistent cookie = has an expiry. Flags: Secure (HTTPS only), HttpOnly (no JavaScript), SameSite (CSRF defence).
Session hijacking = stealing a valid id; session fixation = planting a known id before login → regenerate the id after login, use HTTPS, HttpOnly, short timeouts.
Defaults: PHP — PHPSESSID cookie, gc_maxlifetime 1440 s (24 min). ASP.NET — ASP.NET_SessionId cookie, InProc mode, 20-minute timeout.
01Why HTTP needs state management
HTTP is stateless: a server treats every request as if it were the first, and keeps no memory of earlier requests from the same browser. That design keeps servers simple and lets any server in a farm answer any request. But real applications are conversations: a citizen logs in, fills a three-page application, uploads documents and checks the status — and each page must know who the user is and what happened before.
State is any data that must survive from one request to the next: the identity of the logged-in user, the contents of a cart, the language chosen, the step reached in a wizard, values typed on earlier pages, the current page of a long list. State management is the set of techniques for keeping that data, and the first design decision is where to keep it.
Client-side state
Data travels with the request: cookies, hidden fields, URLs, ViewState
No server memory needed; scales easily
Small and adds to every request
The user can see and change it — never trust it blindly
Server-side state
Data stays on the server: session, application, cache, database
Only an identifier (session id) travels
Can be large and is hidden from the user
Costs server memory or storage and needs sharing in a web farm
Tip
Use the HTTP, forms & sessions tool on this page: submit the login form and watch it become a POST, a Set-Cookie with a session id, and a record in the server's session store.
02Client-side techniques
Technique
How it works
Size / lifetime
Main drawback
Cookie
Server sends Set-Cookie: name=value; the browser returns it in Cookie: on every matching request
About 4 KB each; session or until it expires
Sent with every request; visible and editable; can be disabled
Hidden form field
<input type="hidden" name="step" value="2"> inside a form
Any size with POST; lasts until the next submission
Works only through form submissions; visible in the page source and editable
URL rewriting / query string
State appended to links: apply.php?step=2 or a session id in the URL
A few KB of URL; per link
Visible, bookmarked, logged and leaked in Referer headers and shared links
ViewState (ASP.NET)
Control state serialised into the hidden __VIEWSTATE field
Grows with the page; same page only
Bigger pages; readable unless encrypted
Web Storage
JavaScript localStorage / sessionStorage
About 5 MB; until deleted / tab closes
Never sent automatically; any script on the page can read it (XSS risk)
HTML
<!-- step 2 of an application wizard: answers from step 1 ride along in hidden fields --><form action="apply-step3.php" method="post"><input type="hidden" name="scheme_id" value="7"><input type="hidden" name="category" value="EWS"><label>Annual income <input name="income" type="number" min="0"></label><button>Next</button></form><!-- the same idea with URL rewriting: the state is part of the link --><a href="schemes.php?district=Kollam&page=2">Next page</a>
Watch out
Anything stored on the client can be altered by the user with browser developer tools or a hand-made request. Use client-side state only for harmless data (a page number, a preference); keep authority — who is logged in, prices, eligibility — on the server, or protect the data with a signature (MAC) the server verifies.
With server-side state the browser holds only a short, random identifier; the data itself sits on the server, where the user cannot see or forge it.
Technique
Scope
Lifetime
Typical contents
Session state
One user (one browser)
Until idle timeout or logout
Logged-in user id and name, cart, wizard progress
Application state
All users of the application
Until the application restarts
Hit counters, users online, shared settings (needs locking)
Cache
All users
Until it expires or memory runs short
Results of expensive queries, lists of districts
Database
Anyone with access
Permanent
Profiles, saved carts, applications — survives restarts and works across devices
Session data can be kept in the server's memory (fastest, but lost on restart and not shared between servers), in files (PHP's default), in a database, or in a shared in-memory store such as Redis or ASP.NET's State Service — the usual choice when several servers sit behind a load balancer.
04How a session works end to end
Life of a session
First request
The browser sends no session id, so the server has nothing to look up.
Create
The server generates a long, cryptographically random session id (128 bits or more) and an empty record for it in the session store.
Send the id
The response carries Set-Cookie: PHPSESSID=9f2c…; Path=/; HttpOnly; Secure; SameSite=Lax (ASP.NET names it ASP.NET_SessionId).
Return the id
The browser stores the cookie and attaches it to every later request to that site.
Look up
On each request the server reads the id, loads the matching record and exposes it to the code ($_SESSION, Session[...]).
Update
The code reads and writes values; the store is updated at the end of the request and the idle timer restarts.
End
The session ends after the idle timeout or when the code destroys it at logout; the cookie should be expired as well.
A sliding (idle) timeout expires a session after a period without requests — PHP's session.gc_maxlifetime is 1440 seconds (24 minutes) by default, and ASP.NET's Session.Timeout is 20 minutes. Banking-grade applications add an absolute timeout (for example 8 hours after login, whatever the activity). If the browser refuses cookies, the id can travel in every URL instead (URL rewriting — session.use_trans_sid in PHP, cookieless="UseUri" in ASP.NET), at the cost of leaking it in links.
In a web farm, a session stored in one server's memory is invisible to the others. Either the load balancer sends each user back to the same server (sticky sessions, simple but uneven and fragile when a server fails) or all servers share one session store (a database, Redis, ASP.NET StateServer/SQLServer mode).
Aspect
Cookie
Session
Where the data lives
In the browser
On the server (only the id is in a cookie)
Capacity
About 4 KB per cookie
Limited only by server resources
Data types
Text only
Any serialisable value: arrays, objects
Security
User can read and edit it
Hidden from the user; the risk is theft of the id
Lifetime
Until browser close or the expiry date
Until idle timeout or logout
Cost
Bandwidth on every request
Server memory / storage
Typical use
Preferences, 'remember me' tokens, the session id itself
Login state, carts, wizard data
05Session vs persistent cookies, and cookie security flags
Session (non-persistent) cookie
Set without Expires and without Max-Age
Kept in the browser's memory
Deleted when the browser is closed
Normal for session ids
Persistent cookie
Set with Expires=date or Max-Age=seconds
Written to disk; survives restarts
Deleted at expiry, or earlier by the user or the server
Used for preferences and 'remember me'
Attribute
Security purpose
Secure
Send only over HTTPS, so the id cannot be sniffed on plain HTTP
HttpOnly
Hide the cookie from JavaScript (document.cookie), so an XSS bug cannot read the id
SameSite=Strict
Never send on requests started by other sites — strongest CSRF protection
SameSite=Lax
Send on ordinary links from other sites but not on cross-site POSTs or embedded requests (browsers' default)
SameSite=None
Always send (needed for some cross-site embeds); must also be Secure
Domain / Path
Keep the scope narrow — a cookie for kshb.example also reaches every subdomain
Expires / Max-Age
Short lifetimes limit the damage of a stolen cookie
__Host- name prefix
Browser accepts the cookie only if it is Secure, has Path=/ and no Domain — pins it to one host
TextA hardened session cookie, a 90-day preference cookie, and the header that deletes the preference
06Security: hijacking, fixation, CSRF and tampering
Attack
How it works
Defences
Session hijacking
The attacker obtains a valid session id — by sniffing plain HTTP, through an XSS bug, from a URL in logs or a shared link, or via malware — and replays it
HTTPS everywhere + Secure; HttpOnly; no ids in URLs; short idle and absolute timeouts; regenerate the id at login and privilege changes; re-authenticate before sensitive actions
Session fixation
The attacker gets the victim to use an id the attacker already knows (a crafted link or an injected cookie); after the victim logs in, the attacker uses the same id
Issue a new session id after successful login; reject ids the server never issued (PHP session.use_strict_mode); accept ids only from cookies
Cross-site request forgery (CSRF)
A page on another site makes the victim's browser send a request (e.g. 'transfer' or 'delete'); the browser attaches the victim's cookies automatically
SameSite cookies; a secret anti-CSRF token in a hidden field checked on every state-changing POST; check the Origin header
Parameter tampering
The user edits a hidden field, cookie or query string — e.g. a price or an applicant id
Keep authoritative values on the server; check permissions on every request; sign client-side state
Predictable ids
Sequential or time-based ids can be guessed
Use the platform's cryptographically random session ids — never invent your own
A complete logout
Destroy server data
session_destroy() in PHP or Session.Abandon() in ASP.NET removes the stored record.
Expire the cookie
Send the session cookie again with an expiry in the past so the browser forgets the id.
Redirect
Send the user to the login page; protected pages must check the session on every request, so the Back button shows nothing useful.
PSC favourite
Cookies are the usual way to achieve session persistence (asked in 2026). A web cookie is a small piece of data sent by the website and stored in the user's browser (asked in 2023). Regenerating the session id after login is the cure for session fixation.
07Session APIs side by side: PHP and ASP.NET
Task
PHP
ASP.NET (Web Forms)
Start or resume
session_start(); at the top of every page
Automatic — the Session object is always available
Store a value
$_SESSION["user"] = "anil";
Session["user"] = "anil";
Read a value
$_SESSION["user"] ?? null
(string)Session["user"] — stored as object, so cast
Remove one value
unset($_SESSION["user"]);
Session.Remove("user");
Remove all values
session_unset(); or $_SESSION = [];
Session.Clear();
End the session
session_destroy(); (and expire the cookie)
Session.Abandon();
New id at login
session_regenerate_id(true);
Abandon the old session and expire the ASP.NET_SessionId cookie before redirecting (or rely on a freshly issued authentication cookie)
Idle timeout
session.gc_maxlifetime — 1440 s by default
Session.Timeout or <sessionState timeout="20"> — minutes
Add it again with Expires = DateTime.Now.AddDays(-1)
PHP
<?php
// remember the last district a visitor chose, for 90 days
$district = $_GET["district"] ?? ($_COOKIE["district"] ?? "Kollam");
setcookie("district", $district, time() + 90 * 86400, "/");
session_start();
$_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1; // per session, kept on the server
echo "Showing " . htmlspecialchars($district) . " — visit " . $_SESSION["visits"] . " this session";
C#Cookie for the long-lived preference, session for per-visit data — and output encoding in both
// the same in an ASP.NET page's Page_Load
string district = Request.QueryString["district"]
?? Request.Cookies["district"]?.Value
?? "Kollam";
Response.Cookies.Add(new HttpCookie("district", district) { Expires = DateTime.Now.AddDays(90) });
Session["Visits"] = (Session["Visits"] == null ? 0 : (int)Session["Visits"]) + 1;
lblInfo.Text = "Showing " + Server.HtmlEncode(district) + " — visit " + Session["Visits"] + " this session";
Tip
Whatever the platform, the pattern is identical: one random id in a cookie, data in a server-side store, a timeout, and a fresh id at login. Only the API names differ.
Step through · Login with a server-side session
step 1 / 11
Step 1: POST /login (username, password)
The form is submitted over HTTPS, so the password is encrypted on the wire.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Picking the right technique
Choose a state technique for: (a) answers on pages 1–2 of a 3-page application form until it is finally submitted; (b) the officer who is logged in; (c) a visitor's preferred language for the next 3 months; (d) the number of applications received today, shown to everyone; (e) the price of a unit shown on the booking page before payment.
EX 2A session-fixation attack, step by step
A portal accepts session ids from the URL and keeps the same id after login. Show how an attacker can log in as a victim, and how two settings fix it.
EX 3Timeout arithmetic
A portal uses a 20-minute sliding (idle) timeout and an absolute limit of 8 hours. (a) A clerk's requests arrive at 10:00, 10:15 and 10:40 — what happens at 10:40? (b) Another clerk logs in at 09:00 and sends a request every 5 minutes all day; when must she log in again? (c) What Max-Age gives a 90-day preference cookie?
EX 4Sessions in a web farm
A portal expects 20,000 concurrent sessions of about 4 KB each, served by 3 servers behind a round-robin load balancer, with sessions kept in each server's memory. Estimate the session memory, describe what users will experience, and propose two fixes.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
A booking page stores the unit price in <input type="hidden" name="price" value="1500000">, and the payment script charges whatever price it receives. Describe the attack and the fix.
Q2
Classify each cookie as session or persistent and say when the browser deletes it: (a) sid=91ac; Path=/; HttpOnly (b) theme=dark; Max-Age=0 (c) lang=ml; Expires=Sat, 02 Jan 2027 10:00:00 GMT (d) tour=done; Max-Age=600
Q3
A portal puts the session id in its URLs (welcome.php?PHPSESSID=7c21…), and an officer pastes such a link into a messaging group. Explain the risk and the PHP settings that prevent it.
Q4
Write PHP that (a) stores a logged-in officer's id and name in the session right after a successful password check, safely against fixation, and (b) a guard file required at the top of every protected page that also enforces an 8-hour absolute limit.
Q5
Why is a CSRF attack possible even when the session cookie is HttpOnly and Secure? Name two defences.
Exam traps
Hidden fields are not hidden from the user — they are only not displayed; anyone can read and edit them.
The session cookie carries only the id; the session data stays on the server. Deleting one without the other is an incomplete logout.
HttpOnly stops JavaScript from reading a cookie but does not stop CSRF; SameSite and anti-CSRF tokens do.
Session timeouts are normally idle (sliding) timeouts — activity extends them. Watch the units: PHP's gc_maxlifetime is in seconds (1440), ASP.NET's Timeout in minutes (20).
URL rewriting works without cookies but exposes the session id in links, logs and Referer headers.
Regenerate the session id after login, not before — fixation exploits an id that survives the login.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
State management: cookies, sessions & hidden fields · Question 1 of 10✓ 0 · ✗ 0
Why do web applications need explicit state management?
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 3✓ 0 · ✗ 0
Modelled on QP 050/2026 · Deputy Manager (IT) / Assistant Programmer / Computer Programmer etc (20 May 2026), Q.71 (reworded)original paper (PDF)
Which of these is used to make a session persist across HTTP requests?