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 11: Usage of Cookie

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

Aim

To show the usage of cookies in PHP — setting, reading, updating and deleting them — with a CLI simulation so the full lifecycle is observable in one run.

Theory

A cookie is a small name/value pair the server asks the browser to store and send back with every future request to the same site — it is client-side state. PHP creates one with:

setcookie(name, value, expires, path, domain, secure, httponly)

  • Expiry is an absolute Unix timestamp: time() + 3600 keeps the cookie for one hour. Omitting it creates a session cookie that dies when the browser closes. There is no "delete cookie" call — deletion means re-setting it with a timestamp in the past (time() - 3600), which makes the browser discard it.
  • Timing rule: cookies travel in the Set-Cookie response header, so setcookie() must be called before any output (echo, HTML, even a stray space), or you get the "headers already sent" warning.
  • One-request lag: $_COOKIE is populated from the request headers the browser sent. A cookie set now is therefore visible in $_COOKIE only from the next request onward — the classic exam trap.
  • Security flags: httponly hides the cookie from JavaScript (XSS mitigation), secure restricts it to HTTPS. Cookies are user-editable and size-limited (~4 KB), so never trust them with sensitive data — that is what sessions (Practical 12) are for.

Requirements

  • XAMPP/WAMP with Apache and PHP 8.x (or PHP CLI for the simulated run)
  • Code editor (VS Code); browser with DevTools

Procedure

  1. Start Apache from the XAMPP Control Panel.
  2. Save the snippet as p11_cookie.php in C:\xampp\htdocs\wbplab.
  3. Open http://localhost/wbplab/p11_cookie.php — on the very first visit the read step may show empty values (the one-request lag); refresh and the values appear.
  4. Inspect the cookies in DevTools → Application → Cookies → localhost.
  5. Alternatively run php p11_cookie.php — the CLI branch fills $_COOKIE directly so the whole lifecycle prints in one pass.

Explanation of the Code

  • php_sapi_name() returns the API PHP is running under (cli for terminal, apache2handler/cgi-fcgi under a server). The script branches on it: in web mode it calls real setcookie() with a one-hour expiry and path /; in CLI mode it assigns $_COOKIE keys directly, because there is no browser to store anything.
  • Step 2 reads the three values back from the $_COOKIE superglobal and prints them.
  • Step 3 updates the role: it changes $_COOKIE["user_role"] in memory (so this run prints admin) and, in web mode, also re-issues setcookie() so the browser's copy changes for future requests — both are needed because setcookie() alone would not alter the already-populated array.
  • Step 4 deletes the cookie: web mode re-sets it with time() - 3600 (a past expiry) and both modes unset() the array key; the final isset() check prints No.

Expected Output

The run prints Cookies set successfully., then a Reading cookies block with Name : Rohit Kumar, Email : rohit@example.com, Role : student, then Updated role: admin, then Cookie 'user_role' deleted. and Exists after delete: No. In a browser the same text appears on one page (with the first-visit caveat that the read block needs one refresh before it shows values).

🎯 Viva Questions

  1. Where does a cookie physically live? In the browser (client), which returns it in the Cookie request header on every matching request.
  2. Why must setcookie() precede all output? It writes an HTTP response header; once the body starts, headers are already sent.
  3. Why might $_COOKIE be empty right after setcookie()? $_COOKIE reflects what the browser sent with this request — a new cookie only arrives on the next one.
  4. How is a cookie deleted? By setting it again with an expiry in the past, e.g. time() - 3600; the browser then discards it.
  5. What do the httponly and secure flags do? httponly blocks JavaScript access (XSS defence); secure sends the cookie only over HTTPS.
  6. Cookie vs session — one sentence. A cookie stores data on the client and is user-editable; a session stores data on the server and gives the client only an ID.

CO Mapping

CO1, CO2