PHP Cookies
A cookie is a small piece of data that a PHP script stores in the visitor's browser so information can be remembered across separate requests.
What is a cookie?
HTTP is a stateless protocol, which means the server treats every request as if it has never seen the visitor before. Cookies work around this by asking the browser to hold onto a small labelled value and send it back automatically with every future request to the same site. This lets you recognise a returning visitor, remember a chosen language, or keep track of items in a shopping basket without a database lookup on each page.
In PHP you create and update cookies with the setcookie() function, and you read the values that come back through the $_COOKIE superglobal. Because a cookie travels inside HTTP response headers, setcookie() must be called before any HTML or whitespace is sent to the browser.
Creating a cookie
<?php
$name = "username";
$value = "ada";
$expires = time() + (86400 * 7); // 7 days from now
setcookie($name, $value, $expires, "/");
?>
<html>
<body>
<p>The cookie has been sent to the browser.</p>
</body>
</html>Reading a cookie back
A cookie set on one request is not available in $_COOKIE until the browser sends it back on the next request. For that reason you usually check whether the key exists before using it, using isset() to avoid an undefined-index warning on a visitor's first visit.
Checking and reading a cookie
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . htmlspecialchars($_COOKIE["username"]) . "!";
} else {
echo "Hello, guest. We do not recognise you yet.";
}
?>The setcookie() parameters
Deleting a cookie
There is no dedicated delete function. To remove a cookie you set it again with the same name and path but give it an expiry time in the past. The browser sees that it has already expired and discards it.
Removing a cookie
<?php
// Expire the cookie one hour ago
setcookie("username", "", time() - 3600, "/");
echo "The username cookie has been deleted.";
?>- Cookies are limited to roughly 4 KB, so store identifiers rather than large objects.
- Never store passwords or sensitive data directly in a cookie; keep that on the server in a session.
- Set the httponly and secure flags for anything security related.
- Remember that the user can view, edit, or delete cookies at any time.
Exercise: PHP Cookies
Why must setcookie() be called before any HTML or other output is sent?