PHP Cookies: Creation, Expiration, Deletion & Security Best Practices

Because the HTTP protocol is inherently stateless, the web server does not inherently know whether two requests come from the exact same person. To recognize returning visitors, remember user preferences (such as dark mode vs light mode), or retain shopping carts, websites use Cookies. In PHP, cookies are created on the server and transmitted to the client's web browser via HTTP response headers.

PHP Session vs Cookie Lifecycle Architecture

Figure 5: The lifecycle and architecture of Client-Side Cookies vs Server-Side PHP Sessions.

Syntax of setcookie()

In PHP, you create or modify a cookie using the setcookie() function:

setcookie(name, value, expire, path, domain, secure, httponly);
  • name: The identifier name of the cookie (e.g. "theme").
  • value: The string data stored inside the cookie (e.g. "dark").
  • expire: The Unix timestamp when the cookie expires (e.g. time() + 3600 * 24 * 30 for 30 days). Omitting this makes it a session cookie (deleted when the browser closes).
  • path: Server path where the cookie is available ("/" makes it available across your entire website).
  • secure: If true, the cookie is transmitted only over encrypted HTTPS connections.
  • httponly: If true, prevents JavaScript from accessing the cookie via document.cookie, effectively blocking XSS cookie theft!

Setting and Reading a Cookie

<?php
    // Step 1: Set cookie (MUST be before any HTML output!)
    $cookieName = "preferred_theme";
    $cookieValue = "dark_mode";
    $expirationTime = time() + (86400 * 30); // 86400 seconds = 1 day * 30 days

    // Modern PHP 7.3+ Options Array Syntax (Cleanest & Most Secure):
    setcookie($cookieName, $cookieValue, [
        'expires'  => $expirationTime,
        'path'     => '/',
        'secure'   => true,     // Transmit over HTTPS only
        'httponly' => true,     // Inaccessible to JavaScript (XSS Protection)
        'samesite' => 'Lax'     // CSRF Protection
    ]);
?>

<!-- Step 2: Reading the cookie on subsequent page visits -->
<!DOCTYPE html>
<html>
<body>
<?php
    if (isset($_COOKIE["preferred_theme"])) {
        echo "Active Theme: " . htmlspecialchars($_COOKIE["preferred_theme"]);
    } else {
        echo "Default Theme (Light Mode)";
    }
?>
</body>
</html>

Deleting a Cookie

You cannot delete a cookie directly from server memory because the cookie file resides on the client's machine. To delete a cookie, you instruct the user's browser to discard it by setting its expiration date to a time in the past:

<?php
    // Set expiration date to one hour ago (time() - 3600)
    setcookie("preferred_theme", "", time() - 3600, "/");

    echo "Cookie 'preferred_theme' has been successfully deleted.";
?>

BCA / CS University Exam Corner

High-Frequency Exam Question:

Q: Why should sensitive data like user passwords never be stored in cookies?
A: Cookies reside in plain text files on the user's local hard drive and are transmitted across the internet with every request. Anyone with physical access to the device or network packet inspection tools could read or modify the cookie. Always store sensitive data in Server-Side Sessions.

Interactive Student Practice Session

Exercise 26.1: Create a visit counter using cookies that tracks how many times a user has refreshed the page during the last 24 hours.

Exercise 26.2: Write a script that checks if cookies are enabled in the visitor's browser using count($_COOKIE) > 0 after a test cookie is set.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!