Skip to content

PHP Cookies — Complete Guide to HTTP Cookie Management

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about PHP Cookies. We cover key concepts, practical examples, and best practices to help you master this topic.

PHP cookies store small pieces of data in the user's browser, enabling persistent state like user preferences, login tokens, and tracking across page visits.

What You'll Learn

By the end of this tutorial, you'll set and read cookies, configure expiration, paths, and security flags, use cookies for remember-me functionality, and understand privacy implications.

Why Cookies Matter

HTTP is stateless. Cookies make it stateful. They remember user preferences, shopping cart contents, and authentication state between visits, creating a personalized experience.

Real-World Use

An e-commerce site sets a cookie for the user's preferred currency and language. When they return, the site displays prices in their currency without requiring login.

Cookies Learning Path

flowchart LR
  A[GET/POST] --> B[Cookies]
  B --> C[Sessions]
  C --> D[JSON]
  D --> E[File Handling]
  A --> F{You Are Here}
  style F fill:#f90,color:#fff

Setting Cookies

<?php
setcookie("theme", "dark", time() + 86400 * 30, "/");
setcookie("language", "en", [
    "expires" => time() + 86400 * 365,
    "path" => "/",
    "domain" => "example.com",
    "secure" => true,
    "httponly" => true,
    "samesite" => "Lax"
]);

Reading Cookies

<?php
$theme = $_COOKIE["theme"] ?? "light";
$language = $_COOKIE["language"] ?? "en";
echo "Theme: " . htmlspecialchars($theme);
<?php
setcookie("name", "value", [
    "expires" => time() + 3600,      // 1 hour from now
    "path" => "/admin",               // Only available in /admin
    "domain" => ".example.com",       // Available on subdomains
    "secure" => true,                  // HTTPS only
    "httponly" => true,                // Not accessible via JavaScript
    "samesite" => "Strict"             // CSRF protection
]);

Deleting Cookies

<?php
// Set expiration in the past
setcookie("theme", "", time() - 3600, "/");
setcookie("language", "", [
    "expires" => time() - 3600,
    "path" => "/"
]);

Remember Me Functionality

<?php
$rememberMe = $_POST["remember_me"] ?? false;
if ($rememberMe) {
    $token = bin2hex(random_bytes(32));
    setcookie("remember_token", $token, time() + 86400 * 30, "/", "", true, true);
    // Store token in database linked to user
} else {
    setcookie("remember_token", "", time() - 3600, "/");
}

Common Mistakes

1. Setting Cookies After Output

setcookie() must be called before any HTML output. Buffer output with ob_start() if needed.

2. Not Setting httponly Flag

Without httponly, JavaScript can access cookies (XSS vulnerability). Always set httponly for session cookies.

3. Storing Sensitive Data in Cookies

Cookies are stored on the client and can be read/modified. Never store passwords or credit cards in cookies.

A cookie set for /admin is not available on /. Set the path appropriately for the scope needed.

Users can disable cookies. Your app should handle this gracefully with session fallback or clear messaging.

Practice Questions

1. What is the purpose of the httponly flag?

It prevents JavaScript from accessing the cookie via document.cookie, mitigating XSS Attacks.

2. How do you delete a cookie in PHP?

Set the cookie with an expiration time in the past: setcookie("name", "", time() - 3600).

3. Why must setcookie be called before HTML output?

Cookies are sent in HTTP headers, which must be sent before the response body. Output after headers causes errors.

4. What is the SameSite attribute?

It controls whether cookies are sent with cross-site requests. Strict = same site only. Lax = top-level navigation. None = all requests.

5. Challenge: Create a "remember me" login system using cookies.

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $token = bin2hex(random_bytes(32));
    setcookie("auth_token", $token, [
        "expires" => time() + 86400 * 30,
        "path" => "/",
        "secure" => true,
        "httponly" => true,
        "samesite" => "Strict"
    ]);
    echo "Logged in. Token: $token";
}

FAQ

What is the maximum cookie size?

4KB per cookie. Most browsers limit to ~50 cookies per domain.

Can cookies be accessed across subdomains?

Yes, set the domain parameter: setcookie('name', 'value', ['domain' => '.example.com']).

What is the difference between session and persistent cookies?

Session cookies expire when the browser closes. Persistent cookies have an expiration time set.

Are cookies secure?

Cookies are plain text on the client. Use secure (HTTPS), httponly, and encrypt sensitive values.

How do I see what cookies a website set?

Browser DevTools > Application > Cookies. Shows all cookies with their values and attributes.

Mini Project: Theme Switcher

Build a theme switcher that remembers the user's preference via cookies.

<?php
$theme = $_COOKIE["theme"] ?? "light";
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["theme"])) {
    $theme = $_POST["theme"] === "dark" ? "dark" : "light";
    setcookie("theme", $theme, time() + 86400 * 365, "/");
}
?>
<!DOCTYPE html>
<html><body class="<?= $theme ?>">
<form method="POST">
    <select name="theme">
        <option value="light" <?= $theme === "light" ? "selected" : "" ?>>Light</option>
        <option value="dark" <?= $theme === "dark" ? "selected" : "" ?>>Dark</option>
    </select>
    <button type="submit">Apply</button>
</form>
<style> .dark { background: #333; color: #fff; } </style>
</body></html>

What's Next

PHP Sessions PHP JSON PHP File Handling

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro