Chain
Chain

Reputation: 627

How to Delete all Cookies on my site except for one

I'm using the following function to clear all cookies, which works. This is clearing out the PHPSESSID too as far as I can tell. I want to retain just that one cookie alone.

I added the line: if (name == "PHPSESSID") {... ...to try and catch, and skip, altering the cookie names PHPSESSID, but it doesn't catch it for some reason.

Is there a clear reason why it's not catching, or is there a better way to achieve clearing all cookies except for "PHPSESSID"?

The Function:

function clearCookies() {

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

        }
    }
}

Upvotes: 1

Views: 1239

Answers (1)

Chain
Chain

Reputation: 627

Hi I found the answer by using DevTool's console log instead of the cookie viewer. There's a space in front of PHPSESSID when it's set for some reason. So " PHPSESSID" works.

Solution here: output it in the console log instead of an alert.

Upvotes: 1

Related Questions