Reputation: 9817
I've set a cookie through this call in php
setcookie('alert_msg', 'you have the add badge');
I have tried unsetting it this way
setcookie('alert_msg', '');
setcookie('alert_msg', false);
setcookie('alert_msg', false, 1);
setcookie('alert_msg', false, time()-3600);
setcookie('alert_msg', '', 1, '/');
and it still won't unset the cookie value in $_COOKIE['alert_msg'].
I have tried in both Firefox and Chrome
Code sample:
if (isset($_COOKIE['alert_msg'])) {
$this->set('alert_msg', $_COOKIE['alert_msg']);
unset($_COOKIE['alert_msg']);
setcookie('alert_msg', '', 1, '/');
}
Upvotes: 8
Views: 11992
Reputation: 1693
Sometimes, as per your app design you have to set some cookie details ( for example the path to be something other than / ). Deleting the cookie RELIABLY only works if you can identify that cookie clearly ( everything that you set in it ) for deletion.
Use the code below for reliable deletion;
$params = session_get_cookie_params(); // extract cookie details
unset( $_COOKIE[session_name()] ); // unset the cookie
setcookie(session_name(), " " , 1 ,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"] ); // and also expire the cookie
Note1: Set time to expire to 1 sec past unix epoch time. No need to worry that the user's machine has time correctly set.
Note2: setcookie takes max 7 parameters, so we leave out $params["lifetime"].
The other params are the main ones.
Upvotes: 0
Reputation: 359
In case someone else is having issues with this: in my particular case I was unable to delete a cookie because it was set in the https version of the site and I was visiting the http version. Always redirect to https!
Upvotes: 1
Reputation: 86446
Checkout the cookie path.
Since you are not passing the path
parameter to the setcookie
function, in this case the cookie will be set for the current directory only and can be used and can be unset from that directory only.
Possible solution is to pass the path
value as /
. So that cookie can be used and unset from any part of application.
Upvotes: 21