Remove a cookie

Viewed 702617

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?

23 Answers

You May Try this

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

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.

That will unset the cookie in your code, but since the $_COOKIE variable is refreshed on each request, it'll just come back on the next page request.

To actually get rid of the cookie, set the expiration date in the past:

// set the expiration date to one hour ago
setcookie("hello", "", time()-3600);

See the sample labelled "Example #2 setcookie() delete example" from the PHP docs. To clear a cookie from the browser, you need to tell the browser that the cookie has expired... the browser will then remove it. unset as you've used it just removes the 'hello' cookie from the COOKIE array.

Just set the value of cookie to false in order to unset it:

setcookie('cookiename', false);

If you want to delete the cookie completely from all your current domain then the following code will definitely help you.

unset($_COOKIE['hello']);
setcookie("hello", "", time() - 300,"/");

This code will delete the cookie variable completely from all your domain i.e; " / " - it denotes that cookie variable's value all set for all domain not just for current domain or path. time() - 300 denotes that it sets to a previous time so it will expire.

Thats how it's perfectly deleted.

To remove all cookies you could write:

foreach ($_COOKIE as $key => $value) {
    unset($value);
    setcookie($key, '', time() - 3600);
}

You could set a session variable based on cookie values

session_start();

if(isset($_COOKIE['loggedin']) && ($_COOKIE['loggedin'] == "true") ){
$_SESSION['loggedin'] = "true";
}

echo ($_SESSION['loggedin'] == "true" ? "You are logged in" : "Please Login to continue");

When you enter 0 for time, you mean "now" (+0s from now is actually now) for the browser and it deletes the cookie.

setcookie("key", NULL, 0, "/");

I checked it in chrome browser that gives me:

Name: key
Content: Deleted
Created: Sunday, November 18, 2018 at 2:33:14 PM
Expires: Sunday, November 18, 2018 at 2:33:14 PM

I found that in Chrome it's impossible to unset a cookie unless you define the last three parameters in the cookie... The domain, that it's secure and http only...

if (isset($_COOKIE['user_id'])) {
unset($_COOKIE['user_id']); 
setcookie("user_id", "", time() - 3600, "/", 'yourdomain.com',true,true);
header('Location: /');
} else {
/* other code here */
}

This is how I made it work for me. Read the documentation: All about cookies in the official PHP Site

Related