PHP Cookies
Cookies are small pieces of data stored on the user's browser that persist between page visits. PHP creates cookies using setcookie(), and reads them back through the $_COOKIE superglobal on subsequent requests.
Cookies are often used for remembering user preferences, tracking login state, or storing non-sensitive information across sessions. Because cookies are set before any HTML output, setcookie() must be called before anything is sent to the browser.
setcookie("name", "value", time() + 3600);
$_COOKIE["name"];Setting a cookie
setcookie("name", "value", time() + 3600) creates a cookie named "name" that expires in one hour. The cookie is available on the next page load, not the current one.
Reading and deleting cookies
Read a cookie's value using $_COOKIE["name"]. To delete a cookie, call setcookie() again with an expiration time in the past.
<?php
setcookie("user", "Amy", time() + 3600);
?>(cookie set for next request)This sets a cookie named user with the value Amy, expiring in one hour.
<?php
if (isset($_COOKIE["user"])) {
echo "Welcome back, " . $_COOKIE["user"];
}
?>Welcome back, AmyOn a later request, $_COOKIE reads back the previously stored value.
Key points
- setcookie() creates a cookie on the client's browser.
- Cookies are available starting from the next page load.
- $_COOKIE reads cookie values sent by the browser.
- Deleting a cookie means setting it with a past expiration time.
