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.
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.
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.
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.
Use the setcookie() function. It needs at least a name and a value. Here is the simplest example.
<?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.
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.
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
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.
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
$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.
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
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.
| Option | What it does | Recommended |
|---|---|---|
| expires | When the cookie is deleted by the browser | Set a clear end date |
| path | Which pages can use the cookie | "/" |
| secure | Send only over HTTPS | true |
| httponly | Block JavaScript from reading it | true |
| samesite | Limit cross-site sending | "Lax" |
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
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.
Let us combine everything. This page remembers whether a visitor chose a light or dark theme.
<?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 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.
| Cookie | Session | |
|---|---|---|
| Stored where | In the browser | On the server |
| Can the user edit it? | Yes | No (only the ID is in the browser) |
| Best for | Theme, language, small preferences | Login state, shopping cart |
| Size limit | About 4 KB | Much 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 ExplainedA 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.
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.
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.
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.
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 FepiqOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
What is useRef in React? Learn what a ref is, how it differs from useState, and how to focus an input, with short copy-paste examples for beginners.
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.