Back to the 2023 paper

Module III: Basics of Web Programming

20237m

What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?

Worked SolutionAI Assisted

Significance of cookies

HTTP is stateless, so cookies give websites a memory. They enable:

  • Session management: login state, shopping carts.
  • Personalisation: language, theme, preferences.
  • Tracking and analytics: counting visits, behaviour, advertising.
  • Convenience: "remember me" and auto-filled details.

Creating a cookie in PHP

Syntax: setcookie(name, value, expire, path, domain, secure, httponly);

It must be called before any output (before <html>), because cookies travel in HTTP headers.

<?php
// Create: valid for 1 hour
setcookie("user", "Raiyan", time() + 3600, "/");
?>
<html><body>
<?php
if (isset($_COOKIE["user"])) {
    echo "Hello, " . $_COOKIE["user"];   // available from the next request
} else {
    echo "Cookie not set yet.";
}
?>
</body></html>

Destroying a cookie in PHP

There is no delete function. Set the same cookie with an expiry time in the past (same name, path, and domain):

<?php
setcookie("user", "", time() - 3600, "/");
unset($_COOKIE["user"]);   // also remove it from the current request
?>

The browser sees the cookie has expired and removes it.

Similar questions

Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.