PHP Cookies
A cookie is a small piece of data that your website stores in the browser of the visitor. The browser sends it back to your server with every request. Cookies are used to remember things like a language choice, a theme, or a login (usually with a session).
Create a cookie
Use the setcookie() function. It must be called before any output, because cookies are sent in the HTTP headers. From PHP 7.3 you can pass the options as an array.
<?php
setcookie("username", "Robin", [
"expires" => time() + 3600, // 1 hour from now
"path" => "/",
"secure" => true, // send only over HTTPS
"httponly" => true, // JavaScript can not read it
"samesite" => "Lax"
]);
echo "Cookie is set.";
?>
Output:
Tutorials Class - Output Window
Cookie is set.
| Option | Meaning |
|---|---|
| expires | When the cookie ends, as a time stamp. If you skip it, the cookie is deleted when the browser closes |
| path | The part of the site where the cookie is available. “/” means the whole site |
| secure | Send only on HTTPS |
| httponly | Hide the cookie from JavaScript (protects from theft by XSS) |
| samesite | Controls sending with requests from other sites (Lax or Strict). Helps against CSRF |
Read a cookie
A cookie is not available in the same request that sets it. It is available from the next page load, in the $_COOKIE array.
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . htmlspecialchars($_COOKIE["username"]);
} else {
echo "Hello, new visitor";
}
?>
Output:
On the next page load after the cookie is set
Welcome back, Robin
Delete a cookie
To delete a cookie, set it again with a time in the past. Use the same path as when you created it.
<?php
setcookie("username", "", time() - 3600, "/");
?>
Important points
- The user can see, change and delete cookies. Never trust a cookie value, and never store a password or private data in it.
- A cookie can hold only about 4 KB of data.
- Cookies can be disabled by the user, so your site should work without them for basic things.
- Many countries need a consent from the visitor for cookies that are not essential.
Note:
For a login, store only the session id in the cookie (PHP does it for you) and keep the data on the server. Read PHP Session and cookies vs session.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| Difference Between Cookies and Session |