Back to the 2023 paper

Module III: Basics of Web Programming

20237m

How does the use of cookies help in server-side scripting? Give examples for data stored using cookies.

Worked SolutionAI Assisted

How cookies help in server-side scripting

HTTP is stateless: the server treats every request as new. A server-side script (PHP, Node.js, JSP) can use cookies to recognise a returning client.

Flow:

  1. The script sends a Set-Cookie header in its response.
  2. The browser stores the cookie.
  3. The browser sends it back in the Cookie header on every later request to that site.
  4. The script reads it ($_COOKIE in PHP, req.cookies in Express) and customises the response.

Benefits for server-side scripts:

  • Session tracking: a session ID cookie identifies the logged-in user.
  • Personalisation: language, theme, layout.
  • Remember me: keeps the user signed in across visits.
  • Shopping carts and tracking: cart contents, visited pages, analytics.

Examples of data stored in cookies: username, session ID, preferred language, theme (dark/light), cart ID, last visited page, consent choice.

PHP example:

<?php
setcookie("username", "raiyan", time() + 86400 * 7, "/"); // 7 days

if (isset($_COOKIE["username"])) {
    echo "Welcome back, " . $_COOKIE["username"];
}
?>

Express (JavaScript) example:

res.cookie('theme', 'dark', { maxAge: 86400000, httpOnly: true });
const theme = req.cookies.theme;

Caution: cookies are visible to the client, so never store passwords or sensitive data in them. Use HttpOnly, Secure, and SameSite flags.

Similar questions

Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.