PHP Cookies
The value of a cookie can be modified by resetting the cookie
setcookie("user", "John", time() + 86400, "/");
Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser.
When modifying a cookie make sure the path and domain parameters of setcookie() matches the existing cookie or a new cookie will be created instead.
The value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name
Setting a Cookie
A cookie is set using the setcookie() function. Since cookies are part of the HTTP header, you must set any cookies before sending any output to the browser.
Example:
setcookie("user", "Tom", time() + 86400, "/");
Description:
A created or modified cookie can only be accessed on subsequent requests (where path and domain matches) as the superglobal $_COOKIEis not populated with the new data immediately.
Checking if a Cookie is Set
Use the isset() function upon the superglobal $_COOKIE variable to check if a cookie is set.
Example:
// PHP <7.0
if (isset($_COOKIE['user'])) {
// true, cookie is set
echo 'User is ' . $_COOKIE['user'];
else {
// false, cookie is not set
echo 'User is not logged in';
}
// PHP 7.0+
echo 'User is ' . $_COOKIE['user'] ?? 'User is not logged in';
Removing a Cookie
To remove a cookie, set the expiry timestamp to a time in the past. This triggers the browser's removal mechanism:
setcookie('user', '', time() - 3600, '/');
When deleting a cookie make sure the path and domain parameters of setcookie() matches the cookie you're trying to delete or a new cookie, which expires immediately, will be created.
It is also a good idea to unset the $_COOKIE value in case the current page uses it:
unset($_COOKIE['user']);
Retrieving a Cookie
Retrieve and Output a Cookie Named user
The value of a cookie can be retrieved using the global variable $_COOKIE. example if we have a cookie named user we can retrieve it like this
echo $_COOKIE['user'];