PHP Cookies
PHP cookies are small text files stored on the client side that hold data about the user's behavior and preferences. They are widely used to store information
Introduction to PHP Cookies
PHP cookies are small text files stored on the client side that hold data about the user's behavior and preferences. They are widely used to store information like user preferences, shopping cart contents, or session identifiers.
In this article, we will delve into the basics of PHP cookies and how they can be implemented in a website.
What are PHP Cookies?
A cookie is a small piece of data stored by a website on the user's device. Unlike server-side sessions, cookies reside entirely on the client, making them ideal for lightweight, persistent data like preferences or tracking tokens. PHP creates cookies using the setcookie() function and accesses them via the $_COOKIE superglobal array. The setcookie() function accepts several arguments, including the cookie name, value, expiration time, path, domain, and security flags.
How it works in practice:
- The server sends a cookie. When you call
setcookie(), PHP adds aSet-CookieHTTP response header. The browser stores the cookie. - The browser sends it back. On every subsequent request to the same domain, the browser automatically attaches the cookie in the
Cookierequest header. - PHP reads it. PHP parses incoming cookies into the
$_COOKIEarray, so you can read them on the next page load.
Cookies vs. Sessions
| Cookies | Sessions | |
|---|---|---|
| Where data lives | Client (browser) | Server |
| Survives browser restart | Yes (if expire is in the future) | Only with a persistent session cookie |
| Size limit | ~4 KB per cookie | Limited by server storage |
| Good for | Preferences, "remember me", non-sensitive flags | Login state, sensitive data |
Use cookies for small, non-sensitive data that must persist on the client. Use sessions when the data is sensitive or large.
Creating PHP Cookies
To create a PHP cookie, use the setcookie() function. The basic syntax for the setcookie() function is as follows:
PHP setcookie function syntax
setcookie(name, value, expire, path, domain, secure, httponly);Where:
nameis the name of the cookievalueis the value to be stored in the cookieexpireis the time after which the cookie will expirepathis the path on the server in which the cookie will be availabledomainis the domain name of the websitesecureindicates if the cookie should only be sent over a secure (HTTPS) connectionhttponlyindicates if the cookie should be hidden from JavaScript (document.cookie), which helps protect against XSS attacks
Here's an example of how to create a PHP cookie:
PHP simple example how to add a cookie
setcookie("user", "John Doe", time() + 3600, "/");This code creates a cookie named user with a value of John Doe that expires in one hour (time() returns the current Unix timestamp in seconds, so adding 3600 sets expiry an hour ahead). The "/" path makes the cookie available throughout the entire website.
setcookie() sends an HTTP header, so it must be called before any output — no HTML, whitespace, or echo before it. If output has already started you'll get a "headers already sent" warning and the cookie won't be set. See headers_sent() for how to detect this.
The modern array syntax (PHP 7.3+)
Since PHP 7.3 you can pass an options array instead of positional arguments. This is the recommended form because it lets you set samesite, which controls whether the cookie is sent on cross-site requests (a key CSRF defense):
setcookie("user", "John Doe", [
"expires" => time() + 3600,
"path" => "/",
"secure" => true, // only over HTTPS
"httponly" => true, // not readable by JavaScript
"samesite" => "Lax", // "Strict", "Lax", or "None"
]);Retrieving PHP Cookies
Once a cookie has been created, its value can be retrieved using the $_COOKIE superglobal array. The basic syntax for accessing a cookie value is as follows:
PHP how to get cookie value
$_COOKIE['name'];Where name is the name of the cookie.
Here's an example of how to retrieve a cookie value:
PHP how to access cookie value
if (isset($_COOKIE["user"])) {
echo "Welcome back, " . $_COOKIE["user"];
} else {
echo "Welcome, guest!";
}Always check isset() before reading a cookie. A cookie set on the current request is not available in $_COOKIE until the next page load, because the browser only sends it back on the following request. Reading a freshly set cookie in the same script returns nothing.
Cookie values arrive as untrusted user input — anyone can edit them in their browser. Validate and sanitize them before use, for example with filter_var(). Never trust a cookie value for authorization decisions on its own.
Updating PHP Cookies
To update a PHP cookie, simply create a new cookie with the same name and a new value. The expiration time should also be updated to ensure that the cookie continues to persist.
Here's an example of how to update a PHP cookie:
Example of how to update a cookie
setcookie("user", "Jane Doe", time()+3600, "/", "", 0, 0);This code updates the user cookie with a new value of Jane Doe and extends its expiration time by another hour.
Deleting PHP Cookies
To delete a PHP cookie, simply create a new cookie with the same name and an expiration time in the past. This will cause the cookie to be automatically deleted from the user's device.
Here's an example of how to delete a PHP cookie:
Example of how to delete a cookie
setcookie("user", "", time()-3600, "/", "", 0, 0);This code creates a new user cookie with an expiration time that is one hour in the past. This will cause the cookie to be automatically deleted from the user's device.
To delete a cookie you must pass the same path (and domain) you used when creating it. A cookie set with path /account is a different cookie from one set with path /, and clearing the wrong path leaves the original in place.
A Complete Example: Remembering a Theme Preference
Putting it together, here is a small script that lets a visitor pick a color theme and remembers it across visits using a cookie:
<?php
// 1. Save the choice when the form is submitted
if (isset($_POST["theme"])) {
setcookie("theme", $_POST["theme"], time() + 60 * 60 * 24 * 30, "/"); // 30 days
// Reload so the new cookie is available to $_COOKIE
header("Location: " . $_SERVER["PHP_SELF"]);
exit;
}
// 2. Read the saved choice (default to "light")
$theme = isset($_COOKIE["theme"]) ? $_COOKIE["theme"] : "light";
?>
<p>Current theme: <?= htmlspecialchars($theme) ?></p>
<form method="post">
<button name="theme" value="light">Light</button>
<button name="theme" value="dark">Dark</button>
</form>Note how the script redirects after saving so the freshly set cookie is read on the next request, and how htmlspecialchars() escapes the value before printing it. See PHP form handling for more on processing $_POST data safely.
Advantages of Using PHP Cookies
PHP cookies have several advantages, including:
- Improved User Experience: Cookies allow websites to store user-specific information, such as preferences and login credentials, which can be used to provide a more personalized user experience.
- Persistent Data: Cookies allow websites to store data on the user's device, which can persist even after the user closes the browser or turns off their device. This makes it possible for websites to remember a user's preferences and login credentials across multiple visits.
- Easy Implementation: PHP cookies are easy to implement and can be used to store a wide variety of data, making them a versatile tool for website developers.
Best Practices for Using PHP Cookies
To ensure the best possible user experience and security, it is important to follow best practices when using PHP cookies. Some of these best practices include:
- Use Secure Connections: Whenever possible, use secure connections (HTTPS) when creating and accessing cookies. This will help protect the data stored in cookies from being intercepted by third-party actors.
- Store Sensitive Data Securely: Do not store sensitive data, such as login credentials or passwords, in cookies. Since cookies are stored on the client side, they are vulnerable to theft or tampering. Use server-side sessions (
$_SESSION) for sensitive authentication data instead. - Use Unique Cookie Names: Use unique and descriptive names for your cookies to prevent conflicts with other cookies used by your website or other websites.
- Limit the Amount of Data Stored: Limit the amount of data stored in cookies to only what is necessary. Large amounts of data can slow down website performance and increase the risk of data breaches.
Conclusion
PHP cookies are a powerful tool for website developers, allowing them to store and retrieve data on the user's device. By following best practices and taking security into consideration, PHP cookies can be used to provide a better user experience and increase website functionality.