Cookies

A cookie is a small piece of data PHP asks the visitor's browser to store, and the browser automatically sends back on every later request to the same site. Unlike sessions, cookie data lives on the client, not the server — which makes it perfect for small, non-sensitive preferences that should survive even after the browser is closed and reopened.

1) Setting a Cookie with setcookie()

Just like session_start(), setcookie() must be called before any HTML or other output — it works by sending an HTTP header, and headers can't be sent after the browser has already started receiving the page body.

<?php
  setcookie(
    'favorite_name',          // name
    $name,                       // value
    time() + 86400 * 30,       // expire: 30 days from now
    '/'                          // path: available across the whole site
  );
?>
ParameterMeaning
nameThe cookie's key, used later to read it via $_COOKIE['name']
valueThe string to store (keep it small — no sensitive data)
expireA Unix timestamp; time() + 86400*30 means "30 days from now". Omit/0 means "until the browser closes".
path'/' makes the cookie available on every page of the site, not just the folder that set it

2) Reading a Cookie with $_COOKIE

Once set, the cookie is available on every subsequent request (including different pages) — but not on the very same request that just called setcookie(), since the browser hasn't resent it yet.

<?php
  $name = $_COOKIE['favorite_name'] ?? null;

  if ($name !== null) {
    echo "Welcome back, " . htmlspecialchars($name);
  } else {
    echo "Hi, stranger!";
  }
?>

3) Deleting a Cookie

There's no "delete" function — you overwrite the cookie with an expiration time in the past, which tells the browser to discard it immediately.

<?php
  setcookie('favorite_name', '', time() - 3600, '/');
?>
Note: Use the same path (and domain, if you set one) when deleting a cookie as you used when setting it — otherwise the browser treats it as a different cookie and won't remove the original.

4) Cookies vs Sessions

CookiesSessions
Stored where?Client-side (the visitor's browser)Server-side
Survives browser restart?Yes, if given a future expire timeNo, by default it ends with the browser session
Size limitAbout 4KB per cookieNo practical limit (limited by server resources)
Good forRemembering preferences, "remember me", language choiceLogin state, shopping carts, per-visitor temporary data

5) Working Demo: Remember My Name

Type your name and click Remember Me — PHP sets a real favorite_name cookie that expires in 30 days. Reload the page (or come back tomorrow) and it will greet you by name, straight from $_COOKIE. Click Forget Me to delete the cookie.

Hi, stranger!
Stored in a cookie on your own browser for 30 days.

6) Best Practices & Common Mistakes

IssueProblemFix
Calling setcookie() after output"Headers already sent" warning, cookie never gets setCall it at the very top of the file, before any HTML
Storing sensitive data in a cookieVisitor can read/edit it in DevToolsStore only non-sensitive preferences; use sessions for anything sensitive
Printing a cookie's value unescapedXSS risk if the value is ever attacker-controlledAlways wrap with htmlspecialchars()
Forgetting to match the path when deletingOld cookie doesn't actually get removedUse the exact same path used when it was set

7) Practice Tasks

  1. Add a "theme" cookie (light/dark) that remembers a visitor's choice for 60 days.
  2. Show how many days are left until the favorite_name cookie expires (hint: you'll need to store the expiry separately, since PHP can't read a cookie's expiry back from $_COOKIE).
  3. Build a "recently viewed pages" cookie that stores the last 3 page names as a comma-separated value.
  4. Explain in your own words why cookies alone are not a secure way to store a login/auth state.
Next: Continue with Include & Require — split your PHP code into reusable files.