Remove a cookie – Dev

The best answers to the question “Remove a cookie” in the category Dev.

QUESTION:

When I want to remove a Cookie I try

unset($_COOKIE['hello']);

I see in my cookie browser from firefox that the cookie still exists. How can I really remove the cookie?

ANSWER:

Set the value to “” and the expiry date to yesterday (or any date in the past)

setcookie("hello", "", time()-3600);

Then the cookie will expire the next time the page loads.

ANSWER:

You May Try this

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

ANSWER:

To reliably delete a cookie it’s not enough to set it to expire anytime in the past, as computed by your PHP server. This is because client computers can and often do have times which differ from that of your server.

The best practice is to overwrite the current cookie with a blank cookie which expires one second in the future after the epoch (1 January 1970 00:00:00 UTC), as so:

setcookie("hello", "", 1);

ANSWER:

A clean way to delete a cookie is to clear both of $_COOKIE value and browser cookie file :

if (isset($_COOKIE['key'])) {
    unset($_COOKIE['key']);
    setcookie('key', '', time() - 3600, "https://stackoverflow.com/"); // empty value and old timestamp
}