When I want to remove a Cookie I try
unset($_COOKIE[\'hello\']);
I see in my cookie browser from firefox that the cookie still exists. How
To delete cookie you just need to set the value to NULL:
"If you've set a cookie with nondefault values for an expiration time, path, or domain, you must provide those same values again when you delete the cookie for the cookie to be deleted properly." Quote from "Learning PHP5" book.
So this code should work(works for me):
Setting the cookie:
setcookie('foo', 'bar', time() + 60 * 5);
Deleting the cookie:
setcookie('foo', '', time() + 60 * 5);
But i noticed that everybody is setting the expiry date to past, is that necessary, and why?
I had the same problem in my code and found that it was a cookie path issue. Check out this stack overflow post: Can't delete php set cookie
I had set the cookie using a path value of "/", but didn't have any path value when I tried to clear it, so it didn't clear. So here is an example of what worked:
Setting the cookie:
$cookiePath = "/";
$cookieExpire = time()+(60*60*24);//one day -> seconds*minutes*hours
setcookie("CookieName",$cookieValue,$cookieExpire,$cookiePath);
Clearing the cookie:
setcookie("cookieName","", time()-3600, $cookiePath);
unset ($_COOKIE['cookieName']);
Hope that helps.
If you set the cookie to expire in the past, the browser will remove it. See setcookie() delete example at php.net
You can simply use this customize function:
function unset_cookie($cookie_name) {
if (isset($_COOKIE[$cookie_name])) {
unset($_COOKIE[$cookie_name]);
setcookie($cookie_name, null, -1);
} else { return false; }
}
If you want to remove $_COOKIE['user_account'].
Just use:
unset_cookie('user_account');
You May Try this
if (isset($_COOKIE['remember_user'])) {
unset($_COOKIE['remember_user']);
setcookie('remember_user', null, -1, '/');
return true;
} else {
return false;
}
To remove all cookies you could write:
foreach ($_COOKIE as $key => $value) {
unset($value);
setcookie($key, '', time() - 3600);
}