Back to the 2023 paper

Module III: Basics of Web Programming

202314m

Define session. How it works and what are its advantages?

Worked SolutionAI Assisted

Definition

A session is a way to store information about a user on the server across multiple page requests. Since HTTP is stateless, a session gives each visitor a unique session ID so the server can associate later requests with the same user (login state, cart, preferences).

How it works

  1. Start: the user first visits; the script calls session_start() (PHP) or creates a session (Express, JSP).
  2. ID generation: the server creates a unique random session ID.
  3. Cookie sent: the ID is sent to the browser, usually as a cookie (PHPSESSID), or in the URL if cookies are disabled.
  4. Data stored on the server: values go into $_SESSION and are kept in a file, memory, or database, keyed by the ID.
  5. Later requests: the browser returns the ID; the server loads the matching data.
  6. End: the session ends on logout (session_destroy()), timeout, or when the browser closes.
<?php
session_start();
$_SESSION["user"] = "raiyan";      // page 1

// page 2
session_start();
echo "Logged in as " . $_SESSION["user"];

// logout
session_unset();
session_destroy();
?>

Express equivalent: req.session.user = 'raiyan' using express-session.

Advantages

  1. More secure than cookies: data stays on the server; the client holds only an ID.
  2. Large storage: no 4 KB limit, and any data type (arrays, objects) can be stored.
  3. Works across pages: data is available anywhere within the site during the visit.
  4. Authentication and authorization: keeps users logged in and controls access.
  5. Automatic expiry: sessions time out, limiting misuse.
  6. Client-independent data: the user cannot directly edit stored values.

Drawbacks

Uses server memory or storage, needs the ID transmitted safely (use HTTPS, regenerate the ID on login to stop session fixation), and is harder to scale across multiple servers without a shared store such as Redis.

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.