How Do You Delete A Cookie In PHP?

What Is A Cookie?

It is a type of a small file which is embedded by the server on the computer of a user. The basic purpose of cookies is to identify the user. Every time if a computer will request for a page with any browser, the cookie will be sent too. A cookie value can be both retrieved and created with PHP. A cookie is very helpful for tracking purposes and to retrieve the information. PHP supports HTTP cookies transparently. Read on to know about how to delete a cookie in PHP.

Deleting Cookies With The Set Cookie Option In PHP

The setcookie()can accept almost six arguments, however only a single argument is required and it is the name of the cookie. If the setcookie function is used, and a cookie name is just passed without a value, then it is the same thing as deleting or removing the existing cookie by the same name.

However, as a safety measure, one should set the expiry time to a time from the past – as it can be seen below where and how we pass in “time() – 300″ for the date of expiration. And this is how it is recommended to delete the cookies in PHP:

Set Parameters When Deleting a Cookie In PHP

When deleting a cookie, always remember to use the same parameters that you have used to create those cookies in their first place. For instance, if you set the path and domain when the cookie is created, then those parameters should be used again while deleting the cookie.

Some Other Interesting Facts on Deleting Cookies In The PHP

When you delete a cookie, the deletion actually does not take effect unless the page has been loaded again or a different page has been accessed. It means that the cookie will still be active and available to that page even after deleting that cookie from the same page. However, once you reload the page or access another page in the browser window then only the cookie will be removed or deleted.

Leave a Reply