A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
A cookie is created with the setcookie() function. This function
must appear before any HTML tags.
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly)
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
// Set cookie to expire in 30 days (86400 * 30)
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
To check if a cookie is set and get its value, use the $_COOKIE superglobal
array. Use isset() to avoid errors if the cookie doesn't exist.
<?php
if(!isset($_COOKIE["user"])) {
echo "Cookie named 'user' is not set!";
} else {
echo "Cookie 'user' is set!<br>";
echo "Value is: " . $_COOKIE["user"];
}
?>
To modify a cookie, just set the cookie again using the setcookie() function
with the same name. To **delete** a cookie, use the setcookie() function
with an expiration date in the past.
<?php
// Delete cookie by setting expiry to 1 hour ago
setcookie("user", "", time() - 3600, "/");
?>
httponly parameter (set to true) to
prevent Javascript from accessing the cookie, which helps protect against XSS attacks.
setcookie() to create, modify, and delete data.$_COOKIE array.