Aim
To show the usage of sessions in PHP — starting a session, storing, reading and updating data in $_SESSION, and destroying it on logout.
Theory
HTTP is stateless: each request is independent, so the server has no built-in memory of "who this is". Sessions solve that with a split design: the data lives on the server (by default as a file in PHP's session.save_path), and the client holds only a random session ID, normally carried in a cookie named PHPSESSID.
The lifecycle:
session_start()must run before any output. It either creates a new session (generating a fresh ID) or, if the request carried aPHPSESSIDcookie, reloads that session's stored data into the$_SESSIONsuperglobal.$_SESSIONbehaves like an ordinary associative array; anything written to it is serialised back to the server-side store at script end and reappears on the next request.session_id()returns the current ID;session_status()reports whether a session is already active — checking it againstPHP_SESSION_NONEavoids the "session already started" notice.- Logout is two calls:
session_unset()empties$_SESSIONfor the current request, andsession_destroy()deletes the server-side data so the ID becomes worthless.
Sessions vs cookies: session data is invisible to and unforgeable by the user (only the ID travels), has no 4 KB limit, and can hold arrays/objects — which is why authentication state always belongs in a session, never a cookie. The main risk is session hijacking (stealing the ID), mitigated with session_regenerate_id(true) after login and httponly/secure cookie flags.
Requirements
- XAMPP/WAMP with Apache and PHP 8.x (session support is built in)
- Code editor (VS Code); browser or terminal
Procedure
- Start Apache from the XAMPP Control Panel.
- Save the snippet as
p12_session.phpinC:\xampp\htdocs\wbplab. - Open
http://localhost/wbplab/p12_session.phpand note the printed session ID; check DevTools → Application → Cookies for the matchingPHPSESSID. - Comment out steps 4–5 (update/destroy), reload twice, and confirm the ID stays the same across requests — that persistence is the session.
- Restore the destroy step and verify the final line reports the data gone.
Explanation of the Code
- Step 1 guards the start:
if (session_status() === PHP_SESSION_NONE) { session_start(); }starts a session only when none is active, then printssession_id()— a random alphanumeric token unique to this visitor. - Step 2 stores four values in
$_SESSION, includingdate("Y-m-d H:i:s")as a login timestamp — demonstrating that any serialisable value can be kept. - Step 3 reads the same keys back. Within one request this is a plain array read; across requests it is the reload performed by
session_start(). - Step 4 overwrites
$_SESSION["user_role"]withadmin— updating is just reassignment, no special API. - Step 5 performs the logout pair:
session_unset()clears the array,session_destroy()removes the server-side record. The closingisset($_SESSION["user_name"])check accordingly printsNo.
Expected Output
The script prints Session started. ID: <random id> (e.g. Session started. ID: 7f9c2ba4e88f827d61), then Session data stored., then a Reading session block listing Rohit Kumar, rohit@example.com, student and the current timestamp, then Updated role: admin, and finally Session destroyed (user logged out). with Name exists after destroy: No. The ID value differs on every fresh session.
🎯 Viva Questions
- Where is session data stored, and what does the client keep? Data lives on the server (files by default); the client keeps only the session ID, usually in the
PHPSESSIDcookie. - Why must
session_start()come before any output? It sends the session cookie in a response header, which is impossible once the body has begun. - Difference between
session_unset()andsession_destroy()?session_unset()empties$_SESSIONin the current request;session_destroy()deletes the persisted session data itself. - How does PHP recognise a returning visitor? The browser resends the
PHPSESSIDcookie;session_start()uses it to reload that visitor's stored data. - Why keep login state in a session rather than a cookie? Session data cannot be read or forged by the user — a cookie like
role=admincould simply be edited. - What is session hijacking and one defence? An attacker using a stolen session ID; regenerate the ID after login with
session_regenerate_id(true)and mark the cookiehttponly/secure.
CO Mapping
CO1, CO2