PHP Cookies

A cookie is a small piece of data that a server sends to the user's browser, which stores it and sends it back with every subsequent request to the same server. Cookies are used to remember user preferences, maintain login states (often alongside sessions), track shopping cart contents, or record which pages a user has visited.

Unlike sessions, which store data on the server, cookies store data in the user's browser. This means the data is readable by the user and persists even after the browser is closed — depending on the expiration time set.

Setting a Cookie

The setcookie() function creates a cookie. Like session_start(), it must be called before any HTML output is sent to the browser.

<?php
  // setcookie(name, value, expiry, path, domain, secure, httponly)
  setcookie("username", "alice", time() + (86400 * 30), "/");
  // Expires in 30 days (86400 seconds = 1 day)
?>
<html>
<body>
  <p>Cookie has been set.</p>
</body>
</html>

setcookie() Parameters

ParameterDescription
nameThe name of the cookie
valueThe value to store
expiresUnix timestamp when the cookie expires (0 = session cookie)
pathThe path on the server where the cookie is available ("/" means entire site)
domainThe domain the cookie belongs to (e.g., "example.com")
secureIf true, only send over HTTPS
httponlyIf true, cookie is inaccessible to JavaScript (prevents XSS theft)

Reading a Cookie

Cookies are accessible through the $_COOKIE superglobal. The cookie becomes available on the next page request after it has been set.

<?php
  if (isset($_COOKIE['username'])) {
    $name = htmlspecialchars($_COOKIE['username']);
    echo "Welcome back, " . $name . "!";
  } else {
    echo "No username cookie found.";
  }
?>

Updating a Cookie

Calling setcookie() again with the same name but a new value and expiration time replaces the existing cookie.

<?php
  // Change theme preference
  setcookie("theme", "dark", time() + (86400 * 365), "/");
  echo "Theme updated to dark.";
?>

Deleting a Cookie

To delete a cookie, call setcookie() with the same name but set the expiration time to a time in the past.

<?php
  // Delete the cookie by setting its expiry to the past
  setcookie("username", "", time() - 3600, "/");
  echo "Cookie deleted.";
?>

After this call, the browser will remove the cookie because it has already expired.

Practical Example — Remembering User Preferences

<?php
  // Save a theme preference
  if (isset($_POST['theme'])) {
    $theme = $_POST['theme'] === 'dark' ? 'dark' : 'light';
    setcookie("theme", $theme, time() + (86400 * 365), "/");
    $currentTheme = $theme;
  } else {
    $currentTheme = $_COOKIE['theme'] ?? 'light';
  }
?>

<html>
<body class="theme-<?= htmlspecialchars($currentTheme) ?>">

  <p>Current theme: <?= htmlspecialchars($currentTheme) ?></p>

  <form method="post" action="">
    <button name="theme" value="light">Light Mode</button>
    <button name="theme" value="dark">Dark Mode</button>
  </form>

</body>
</html>

Cookie Limitations and Security Considerations

Storage Limits

  • Browsers typically allow a maximum of 4KB per cookie.
  • Most browsers limit the number of cookies per domain to 50.
  • Cookies are sent with every HTTP request, so large cookies slow down requests.

Security Practices

  • Never store sensitive data (passwords, credit card numbers) in cookies — they are readable by the user and can be tampered with.
  • Set the httponly flag to true to prevent JavaScript from accessing the cookie (protects against XSS).
  • Set the secure flag to true so cookies are only sent over HTTPS connections.
  • Always sanitize cookie values before using them, just like any other user input.
<?php
  // Secure cookie example
  setcookie(
    "user_pref",         // name
    "dark-theme",        // value
    time() + 86400,      // expires in 24 hours
    "/",                 // path
    "",                  // domain (empty = current domain)
    true,                // secure (HTTPS only)
    true                 // httponly (no JavaScript access)
  );
?>

Sessions vs Cookies

FeatureSessionsCookies
Data storage locationServerBrowser
SecurityMore secureLess secure (user can edit)
Data size limitNo practical limit~4KB per cookie
PersistenceUntil session ends or expiresUntil expiration date or deletion
Best forLogin state, sensitive dataPreferences, analytics, remember-me

Key Points

  • setcookie() must be called before any HTML output is sent.
  • Cookies are accessed via $_COOKIE['name'] on the next request after they are set.
  • Delete a cookie by calling setcookie() with the same name and an expiration time in the past.
  • Always use isset() when reading cookies — they may not exist if the user deleted them.
  • Set secure and httponly flags for cookies that hold important data.
  • Never store sensitive information in cookies — store only preferences or non-sensitive identifiers.

Leave a Comment

Your email address will not be published. Required fields are marked *