How to Delete a Cookie in PHP
In this article, you will learn how to delete a cookie in PHP.
Using setcookie() function
In PHP, cookies are created and managed through the use of the setcookie() function. The function requires at least two parameters: the name of the cookie and its value. The cookie is then stored on the user’s browser and sent with every subsequent request to the website.
To delete a cookie, you simply call the setcookie() function with the same name as the cookie you want to delete and an expiration date in the past. This sets the expiration date of the cookie to a time that has already passed, effectively telling the browser to remove it.
<?php setcookie("cookie_name", "", time() - 3600); ?>
In this example, the name of the cookie is “cookie_name”. The value of the cookie is set to an empty string, and the expiration date is set to one hour ago, using the time() function. This causes the browser to delete the cookie.
It’s important to note that the setcookie() function must be called before any output is sent to the browser. If you try to call it after sending output, you’ll get a warning and the cookie will not be deleted.