How to Remove a Cookie with PHP
In this snippet, we will provide you with the most accurate method to remove a cookie using PHP.
However, before learning how to remove a cookie, let’s see how to create it.
Creating a Cookie
If you intend to create a cookie, you can use the setcookie() function.
The syntax of the setcookie() function will look as follows:
setcookie(name, value, expire, path, domain, secure, httponly)
And here is an example of creating a cookie with this function:
<!DOCTYPE html>
<?php
$cookie_name = "gfg";
$cookie_value = "W3docs";
// 86400 = 1 day
setcookie($cookie_name, $cookie_value, time() + 86400 * 15, "/");
?>
<html>
<body>
<?php if (!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
} ?>
</body>
</html>
Removing a Cookie
There is no specific function for deleting a cookie in PHP. However, we recommend you to use the PHP setcookie() function mentioning the expiration date in the past as demonstrated below:
<?php
// setting the expiration date to an hour ago
setcookie("user", "", time() - 3600); ?>
<html>
<body>
<?php echo "Cookie 'user' is deleted."; ?>
</body>
</html>
What is a Cookie?
As a rule, cookies are used for identifying a user. It is a small file, which the server embeds on the computer of the user.
Every time the user’s computer gets to request a page with a browser, a cookie will be sent, as well.
PHP allows creating, modifying and removing cookies.