All posts
PHPOctober 25, 20267 min read

PHP Cookies Explained for Beginners (With Examples)

Learn what PHP cookies are and how to set, read and delete them with setcookie(). Simple examples and line-by-line explanations for absolute beginners.

F
Fepiq Team
Fepiq

What are PHP cookies, and how do you use them? A cookie is a tiny piece of text that your website asks the visitor's browser to save. In PHP, you create one with the setcookie() function and read it back with the $_COOKIE variable. In this beginner guide, you will learn both, step by step, with small examples you can copy and run.

What is a cookie?

A web server forgets you the moment it sends a page. It does not remember who you are on the next visit. A cookie solves this. The server sends a small note, such as theme=dark, and the browser stores it. On every later request to the same site, the browser sends the note back.

Common uses for cookies are remembering a language choice, a light or dark theme, or the fact that someone closed a welcome banner. A cookie is small text data. It is not a program, and it cannot run code.

How to set a cookie in PHP

Use the setcookie() function. It needs at least a name and a value. Here is the simplest example.

php
<?php
setcookie("username", "Maria");

echo "Cookie has been set!";
?>

Line 2 asks the browser to save a cookie named username with the value Maria. Line 4 prints a message. This cookie has no end date, so it lasts only until the visitor closes the browser. That is called a session cookie.

Important rule: call setcookie() first

Cookies travel in the HTTP headers, which are sent before the page content. So you must call setcookie() before any output. Output means any echo, any HTML, or even a blank line before the opening PHP tag. If you break this rule, PHP shows a warning that says headers were already sent.

How to read a cookie in PHP

PHP puts all cookies sent by the browser into a special array called $_COOKIE. An array is a list of values, and here each value has a name. Always check that the cookie exists before you use it.

php
<?php
if (isset($_COOKIE["username"])) {
    echo "Welcome back, " . htmlspecialchars($_COOKIE["username"]);
} else {
    echo "Hello, new visitor!";
}
?>

Line 2 uses isset() to ask: does a cookie called username exist? If yes, line 3 prints a greeting. The htmlspecialchars() function makes the text safe to show on a page. Line 5 runs for first-time visitors.

There is one surprise. A cookie you set with setcookie() is not in $_COOKIE during the same request. It appears on the next page load, because the browser only sends it back later.

Make a cookie last longer with an expiry time

The third argument of setcookie() is the expiry time. It is a Unix timestamp, which counts seconds since January 1, 1970. The easy way is to take the current time with time() and add some seconds.

php
<?php
$thirtyDays = time() + (60 * 60 * 24 * 30);

setcookie("theme", "dark", $thirtyDays, "/");
?>

Line 2 works out the moment 30 days from now: 60 seconds times 60 minutes times 24 hours times 30 days, added to the current time. Line 4 saves a cookie named theme with the value dark until that moment. The last argument, "/", is the path. It makes the cookie available on every page of your site, not only the current folder.

Use safer cookie options

Since PHP 7.3 you can pass an array of options. This is easier to read and lets you turn on important security settings.

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

Each line inside the array is one setting. expires is when the cookie dies. path is where it works. secure sends it only over HTTPS. httponly hides it from JavaScript, which protects against some attacks. samesite limits sending it from other websites, which helps against another kind of attack called CSRF. Turn these on by default.

OptionWhat it doesRecommended
expiresWhen the cookie is deleted by the browserSet a clear end date
pathWhich pages can use the cookie"/"
secureSend only over HTTPStrue
httponlyBlock JavaScript from reading ittrue
samesiteLimit cross-site sending"Lax"

How to delete a cookie

PHP has no deleteCookie() function. Instead, you set the same cookie again with an expiry time in the past. The browser then removes it.

php
<?php
setcookie("theme", "", time() - 3600, "/");
?>

The value is empty, and the expiry time is one hour ago (time() - 3600). The path must match the path you used when you created the cookie, or the browser will not delete it.

A small real example: remember the theme

Let us combine everything. This page remembers whether a visitor chose a light or dark theme.

php
<?php
$allowed = ["light", "dark"];

if (isset($_GET["theme"]) && in_array($_GET["theme"], $allowed)) {
    setcookie("theme", $_GET["theme"], time() + 86400 * 30, "/");
    $theme = $_GET["theme"];
} elseif (isset($_COOKIE["theme"]) && in_array($_COOKIE["theme"], $allowed)) {
    $theme = $_COOKIE["theme"];
} else {
    $theme = "light";
}
?>
<body class="<?= $theme ?>">
  <a href="?theme=light">Light</a> |
  <a href="?theme=dark">Dark</a>
</body>

Line 2 lists the two themes we accept. Lines 4 to 6 run when the visitor clicks a link such as ?theme=dark: we check the value is allowed, save it in a cookie for 30 days, and use it right away. Lines 7 to 8 run on later visits and read the saved cookie. Line 10 is the default. Checking the value against a list matters, because users can edit cookies and URLs freely.

Cookies vs sessions: which should you use?

Cookies are stored in the visitor's browser, so the visitor can see and change them. Sessions keep data on the server and only put a random ID in a cookie. Never store passwords or private data in a normal cookie.

CookieSession
Stored whereIn the browserOn the server
Can the user edit it?YesNo (only the ID is in the browser)
Best forTheme, language, small preferencesLogin state, shopping cart
Size limitAbout 4 KBMuch larger

Want to keep a user logged in safely? Learn how sessions store data on the server instead of in the browser.

Read: PHP Sessions Explained

Common beginner mistakes

  • Printing something before calling setcookie(), which causes the headers already sent warning.
  • Expecting a new cookie to appear in $_COOKIE on the same page load.
  • Forgetting the path when deleting, so the cookie stays.
  • Trusting cookie values without checking them. Always validate and escape.
  • Storing sensitive data such as passwords in a cookie.

Frequently asked questions

What is a cookie in PHP?+

A cookie is a small piece of text that your PHP code asks the browser to store. The browser sends it back with each request to your site. You create it with setcookie() and read it with $_COOKIE.

Why is my PHP cookie not working?+

The most common cause is output before setcookie(), such as an echo or a blank line before the PHP tag. Also remember that a new cookie shows up in $_COOKIE only on the next request. Check that your path and expiry values are correct.

How long does a PHP cookie last?+

If you give no expiry time, it lasts until the browser closes. If you set one, for example time() + 86400 * 30, it lasts for that many seconds, here 30 days. The browser deletes it afterwards.

How do I delete a cookie in PHP?+

Call setcookie() again with the same name and path, an empty value, and an expiry time in the past, like time() - 3600. The browser then removes the cookie.

Are PHP cookies safe?+

Cookies are fine for small preferences, but users can read and change them. Turn on the secure, httponly and samesite options, validate every value, and never store passwords or private data in them.

Need help building a PHP website or web app? Our team can help you plan and build it.

Talk to Fepiq

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.