The $_COOKIE superglobal in PHP is used to retrieve data stored in cookies. Cookies allow small pieces of data to persist in the user's browser across multiple page loads.
$_COOKIEThe setcookie() function is used to create cookies.
// Syntax for setting a cookie in PHP
setcookie(name, value, expire, path, domain, secure, httponly);
This example sets a cookie named user that expires in one hour.
// Set a cookie that expires after one hour
<?php
setcookie("user", "JohnDoe", time() + 3600, "/");
echo "Cookie has been set!";
?>
// Check and read cookie value
<?php
if(isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"];
} else {
echo "Cookie not set.";
}
?>
If the cookie exists, its value is displayed. Otherwise, a fallback message is shown.
// Delete a cookie by setting expiration in the past
<?php
setcookie("user", "", time() - 3600, "/");
echo "Cookie has been deleted!";
?>
Cookies are commonly used to remember theme preferences, login state, or language selection across page reloads.
setcookie() before any outputhttponly and secure flags for security