Cookies stay in a user’s system unless they expire or are removed by the server which has transmitted them in the first place. In PHP, removing cookies process can be done while creating a cookie by setting its expiry duration. Means that when a cookie is created its expires argument can be set with expiry so that it gets terminated from a user’s system after this set time. If a web developer wants to remove a cookie from users’ system before it actually expires, she can do so by using the setcookie() function.
Why to remove cookie?
There can be many reasons for removing cookies-
- A cookie is no longer relevant
- A cookie is hijacked by a hacker and sends data that poses certain threats to a website.
- You need to define altogether new cookies for your website
- You need to collect different set of user data with cookies.
Removing Cookies in PHP script
When developer decides to get rid of a cookie stored in a user’s system, she can remove it by instructing the browser. Each existing cookie can be deleted by calling a separate setcookie() function by passing the name of the cookie. Here you don’t need to set any valid value for cookie. It can be set to an empty string. The most important argument in the setcookie() function to remove it is the expires argument. It must be a time in the past.
The cookie to be deleted must be exactly the same as per its existing definition since you won’t wish to delete a wrong cookie. For this the path, the domain, secure and httponly fields’ values must be the same with which the cookie is currently stored with. If a cookie is never updated then use the same field values when it was first created. If the cookie was updated then you must use the latest updated attributes’ values except expires attribute.
When a browser gets a script with expires argument value representing past time, it immediately deletes it from the cookies file in the user’s system.
Example Removing Cookies in PHP scripts
setcookie( “userVisits”, “”,time() - 3600); setcookie('email','email@example.com', time()-3600*24*30, ‘/phpTutorial/’,’csveda.com’, TRUE);
In the above examples expiry time is set to 3600 seconds (one hour) in the past. Both UserVisits and email cookies will be removed from the cookies file in the system path discussed in earlier post. A deleted cookie will continue to be available in the page which executed the script to delete it. The simple explanation to this behavior is that the $_COOKIE associative array gets all details of the website’s cookies when the page was loaded.
The removing cookie PHP scripts executes and removes cookie from system but it stays in $_COOKIE. The deleted cookie is cleared from this array when the page loads again or the page is sent again by the server after browser’s new request.