Delete Cookie by Name

Delete cookie by name?

You should define the path on which the cookie exists to ensure that you are deleting the correct cookie.

function set_cookie(name, value) {
document.cookie = name +'='+ value +'; Path=/;';
}
function delete_cookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

If you don't specify the path, the browser will set a cookie relative to the page you are currently on, so if you delete the cookie while on a different page, the other cookie continues its existence.

Edit based on @Evan Morrison's comment.
Be aware that in some cases to identify the correct cookie, the Domain parameter is required.
Usually it's defined as Domain=.yourdomain.example.
Placing a dot in front of your domain name means that this cookie may exist on any sub-domain (www also counts as sub-domain).

Also, as mentioned in @RobertT's answer, HttpOnly cookies cannot be deleted with JavaScript on the client side.

How to delete a cookie if I only know its name's first few characters - with Javascript?

You could just remove the cookie value using:

function removeCookieValue(name) {
document.cookie = name+'="";-1; path=/';
}

removeCookieValue('_ga')

Clearing all cookies with JavaScript

function deleteAllCookies() {
var cookies = document.cookie.split(";");

for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}

Note that this code has two limitations:

  • It will not delete cookies with HttpOnly flag set, as the HttpOnly flag disables Javascript's access to the cookie.
  • It will not delete cookies that have been set with a Path value. (This is despite the fact that those cookies will appear in document.cookie, but you can't delete it without specifying the same Path value with which it was set.)

Remove a cookie

You May Try this

if (isset($_COOKIE['remember_user'])) {
unset($_COOKIE['remember_user']);
setcookie('remember_user', null, -1, '/');
return true;
} else {
return false;
}


Related Topics



Leave a reply



Submit