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() + 3600keeps 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-Cookieresponse header, sosetcookie()must be called before any output (echo, HTML, even a stray space), or you get the "headers already sent" warning. - One-request lag:
$_COOKIEis populated from the request headers the browser sent. A cookie set now is therefore visible in$_COOKIEonly from the next request onward — the classic exam trap. - Security flags:
httponlyhides the cookie from JavaScript (XSS mitigation),securerestricts 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
- Start Apache from the XAMPP Control Panel.
- Save the snippet as
p11_cookie.phpinC:\xampp\htdocs\wbplab. - 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. - Inspect the cookies in DevTools → Application → Cookies →
localhost. - Alternatively run
php p11_cookie.php— the CLI branch fills$_COOKIEdirectly so the whole lifecycle prints in one pass.
Explanation of the Code
php_sapi_name()returns the API PHP is running under (clifor terminal,apache2handler/cgi-fcgiunder a server). The script branches on it: in web mode it calls realsetcookie()with a one-hour expiry and path/; in CLI mode it assigns$_COOKIEkeys directly, because there is no browser to store anything.- Step 2 reads the three values back from the
$_COOKIEsuperglobal and prints them. - Step 3 updates the role: it changes
$_COOKIE["user_role"]in memory (so this run printsadmin) and, in web mode, also re-issuessetcookie()so the browser's copy changes for future requests — both are needed becausesetcookie()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 modesunset()the array key; the finalisset()check printsNo.
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
- Where does a cookie physically live? In the browser (client), which returns it in the
Cookierequest header on every matching request. - Why must
setcookie()precede all output? It writes an HTTP response header; once the body starts, headers are already sent. - Why might
$_COOKIEbe empty right aftersetcookie()?$_COOKIEreflects what the browser sent with this request — a new cookie only arrives on the next one. - How is a cookie deleted? By setting it again with an expiry in the past, e.g.
time() - 3600; the browser then discards it. - What do the
httponlyandsecureflags do?httponlyblocks JavaScript access (XSS defence);securesends the cookie only over HTTPS. - 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