Is there any way of instructing a web browser to completely delete one\'s cookie set with PHP?
I do not want to expiry it or wait for the brows
'Seems that deleting a cookie is more difficult than it looks.
setcookie($name, '', 1);
Won't do the trick. The ''
is empty and setcookie
can ignore the whole instruction.
Also setting the time to the past sometimes allows the cookie to retain the value whose expire time is newer than 1.
I am dealing with this right now. I don't know where it comes from, but it's there.
I've resorted to
setcookie($name, '0', 9000000000);
This ensures the cookie is set to a value that resolves to false and that it is newer than any previous value.
If anyone has any insight into this behavior please tell.
I suspect the difficulty lies in the fact that the domain and path values for setcookie
are guaranteed to be the same from execution to execution when the values are not specified.
And I am aware such a cookie will not expire until 2038 or so.
Alternately, if the newest expiration date of the cookie is known, it need be set only 1 second after.
Yes. Use setcookie()
and set the expiration date for the cookie you wish to delete to a time in the past. The user's browser should automatically remove it as a result.
I think that you have to use combined approach:
There are 2 good reasons for going with mixed approach:
I wrote this plugin for me and works correctly.
(function($) {
$.cookieAllDelete = function(doc)
{
var cookie_date = new Date();
var cookies = null;
cookies = doc.cookie.split(';');
cookie_date.setTime(cookie_date.getTime() - 1);
for(var i=0; i < cookies.length; i++)
{
var cookie_name = cookies[i].split('=')[0];
try {
if (cookie_name.length > 0)
doc.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
} catch(ex) {}
}
}
})(jQuery);
jQuery.cookieAllDelete(document);
You cannot force the browser to delete the file associated with any cookie, because you can't guarantee there's actually such a file - the contract between browser and web server regarding cookies is that the data will be presented at eligible requests.
You state that you "don't want to wait for the cookie to expire", but cookie expiration is the correct method for indicating that the data is no longer needed and should not be presented on future requests, which in most cases does translate to the browser removing the file.
To delete a cookie, therefore, set its expiration time into the past. In PHP, this is done with setcookie().
Try something like this to delete all cookies:
foreach ($_COOKIE as $name => $value) {
setcookie($name, '', 1);
}
The value 1
is the expire value and it represents one second after the begin of the Unix time epoch. So it’s always already expired.