LearnContact
Lesson 3520 min read

Cookies

Learn what cookies are and how to set, read, and secure small pieces of data stored in a visitor's browser.

Introduction

Websites that remember your language preference, keep you logged in across visits, or recall the last theme you chose are usually relying on a small piece of data stored right in your browser: a cookie. PHP has built-in support for creating and reading cookies without any extra libraries.

This lesson explains what a cookie is, how to set one with setcookie(), how to read it back on a later request with $_COOKIE, and a few security-related flags worth knowing about.

What You Will Learn
  • What a cookie is and how it travels between the browser and the server.
  • How to set a cookie with setcookie().
  • How to read a cookie's value using the $_COOKIE superglobal.
  • What the httponly and secure flags do.
  • Typical real-world use cases for cookies.

A cookie is a small piece of data — typically just a name and a value — that a server asks the visitor's browser to store. Once stored, the browser automatically sends that cookie back to the server with every subsequent request to the same site, until it expires.

Stored in the Browser

Cookies live on the visitor's machine, not on the server.

Sent with Every Request

Once set, the browser automatically attaches the cookie to future requests to the same domain.

Has an Expiration

A cookie can be set to expire after a specific time, or when the browser closes.

Small Only

Cookies are meant for small values — a few kilobytes at most, not large data.

Setting a Cookie

The setcookie() function schedules a cookie to be sent to the browser. It must be called before any HTML or other output is sent, since cookies are transmitted as part of the HTTP response headers.

set-cookie.php
<?php
// Set a cookie named "theme" with the value "dark", expiring in one hour
setcookie("theme", "dark", time() + 3600);
echo "Cookie has been set.";
?>
Example Output
Cookie has been set.
Call setcookie() Before Any Output

setcookie() sends an HTTP header, so it must run before any echo, HTML, or even a blank line above the opening <?php tag — otherwise PHP will emit a "headers already sent" warning and the cookie will not be set.

Reading a Cookie

Once a cookie has been set, it becomes available on every later request through the $_COOKIE superglobal — but only starting from the next page load, since the browser needs to receive and store it first.

read-cookie.php
<?php
if (isset($_COOKIE["theme"])) {
    echo "Current theme: " . htmlspecialchars($_COOKIE["theme"]);
} else {
    echo "No theme cookie set yet.";
}
?>
Example Output
Current theme: dark

Deleting a Cookie

There is no dedicated "delete" function — instead, you set the same cookie again with an expiration time in the past, which tells the browser to remove it immediately.

delete-cookie.php
<?php
setcookie("theme", "", time() - 3600);
echo "Theme cookie removed.";
?>
Example Output
Theme cookie removed.

setcookie() accepts additional options that make cookies safer to use, especially for anything sensitive like a login token.

FlagPurpose
httponlyPrevents client-side JavaScript from reading the cookie, reducing the impact of certain attacks.
secureEnsures the cookie is only sent over HTTPS connections, never plain HTTP.
secure-cookie.php
<?php
setcookie("remember_token", "abc123", [
    "expires" => time() + (86400 * 30),
    "path" => "/",
    "httponly" => true,
    "secure" => true,
]);
?>
Use the Options Array on Modern PHP

Since PHP 7.3, setcookie() accepts an options array (as shown above) instead of a long list of positional arguments, making flags like httponly and secure much clearer to read.

Typical Use Cases

Remembering Preferences

Storing a visitor's chosen theme, language, or layout so it persists across visits.

"Remember Me" Tokens

Storing a long-lived token so a visitor stays logged in without re-entering credentials every visit.

Basic Tracking

Recognizing a returning visitor for analytics, without necessarily identifying who they are personally.

Guest Shopping Carts

Keeping track of cart contents for a visitor who has not created an account.

Example: Remembering a Theme Preference

A complete, small example: set a theme cookie the first time a visitor picks one, and read it back on every later visit to apply the correct styling.

theme.php
<?php
if (isset($_GET["theme"])) {
    setcookie("theme", $_GET["theme"], time() + (86400 * 30));
    $theme = $_GET["theme"];
} else {
    $theme = $_COOKIE["theme"] ?? "light";
}

echo "Using theme: " . htmlspecialchars($theme);
?>
Example Output
Using theme: dark

Common Mistakes

Avoid These Mistakes
  • Calling setcookie() after HTML has already been echoed, causing a "headers already sent" error.
  • Expecting a newly set cookie to appear in $_COOKIE on the very same request — it only becomes available on the next request.
  • Storing sensitive data like passwords directly inside a cookie.
  • Forgetting the httponly and secure flags on cookies that hold anything sensitive, like a remember-me token.

Best Practices

  • Set cookies before any output, ideally at the very top of the script.
  • Always check isset() before reading a value from $_COOKIE.
  • Use the httponly and secure flags for any cookie holding an authentication-related value.
  • Keep cookie values small and avoid storing anything sensitive in plain text.
  • Give cookies a sensible expiration time rather than making everything last forever.

Frequently Asked Questions

How large can a cookie be?

Most browsers limit individual cookies to around 4KB, so cookies are meant for small values, not large data.

Do cookies work across different websites?

No, by default a cookie is only sent back to the domain that set it, which keeps one site from reading another site's cookies.

What is the difference between a session cookie and a persistent cookie?

A session cookie has no expiration set and disappears when the browser closes, while a persistent cookie includes an expiration time and survives across browser restarts.

Can JavaScript read a cookie set with httponly?

No, that is exactly what httponly prevents — it makes the cookie accessible only to the server, not to client-side scripts.

Is it safe to store a user ID directly in a cookie?

It is risky on its own since cookies can be edited by the visitor; sensitive identity data is usually better handled through sessions, covered in the next lesson.

Key Takeaways

  • A cookie is a small piece of data stored in the visitor's browser and resent with every request.
  • setcookie('name', 'value', time() + 3600) sets a cookie that expires in one hour.
  • Cookies are read on later requests through the $_COOKIE superglobal.
  • The httponly and secure flags make cookies safer against common attacks.
  • Cookies are commonly used for preferences and "remember me" functionality.

Summary

Cookies give PHP a way to store small pieces of data directly in a visitor's browser, which then gets sent back automatically with every future request. Setting one is as simple as calling setcookie(), and reading it back just means checking $_COOKIE on the next page load.

In this lesson, you learned how to set, read, delete, and secure cookies, along with common real-world use cases. Next, you will learn about sessions — a server-side alternative that solves many of the same problems more securely.

Lesson 35 Completed
  • You understand what a cookie is and how it travels between browser and server.
  • You can set a cookie with setcookie().
  • You can read a cookie with $_COOKIE.
  • You know the purpose of the httponly and secure flags.
Next Lesson →

Sessions