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%

Practical 12: Usage of Session

Lesson 19 of 35 in the free Web Based Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

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 a PHPSESSID cookie, reloads that session's stored data into the $_SESSION superglobal.
  • $_SESSION behaves 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 against PHP_SESSION_NONE avoids the "session already started" notice.
  • Logout is two calls: session_unset() empties $_SESSION for the current request, and session_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

  1. Start Apache from the XAMPP Control Panel.
  2. Save the snippet as p12_session.php in C:\xampp\htdocs\wbplab.
  3. Open http://localhost/wbplab/p12_session.php and note the printed session ID; check DevTools → Application → Cookies for the matching PHPSESSID.
  4. Comment out steps 4–5 (update/destroy), reload twice, and confirm the ID stays the same across requests — that persistence is the session.
  5. 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 prints session_id() — a random alphanumeric token unique to this visitor.
  • Step 2 stores four values in $_SESSION, including date("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"] with admin — 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 closing isset($_SESSION["user_name"]) check accordingly prints No.

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

  1. 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 PHPSESSID cookie.
  2. 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.
  3. Difference between session_unset() and session_destroy()? session_unset() empties $_SESSION in the current request; session_destroy() deletes the persisted session data itself.
  4. How does PHP recognise a returning visitor? The browser resends the PHPSESSID cookie; session_start() uses it to reload that visitor's stored data.
  5. 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=admin could simply be edited.
  6. 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 cookie httponly/secure.

CO Mapping

CO1, CO2