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 browser to be closed.
With delete I mean to actually not have it listed inside the cookie's list anymore.
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 browser to be closed.
With delete I mean to actually not have it listed inside the cookie's list anymore.
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 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);
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.
I think that you have to use combined approach:
There are 2 good reasons for going with mixed approach:
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()
.