Remove a cookie

PhpCookies

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

You May Try this

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

Solution 2 - Php

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.

Solution 3 - Php

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, '/'); // empty value and old timestamp
}

Solution 4 - Php

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);

Solution 5 - Php

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);

Solution 6 - Php

I had the same problem in my code and found that it was a cookie path issue. Check out this stack overflow post: https://stackoverflow.com/questions/6187132/cant-delete-php-set-cookie

I had set the cookie using a path value of "/", but didn't have any path value when I tried to clear it, so it didn't clear. So here is an example of what worked:

Setting the cookie:

$cookiePath = "/";
$cookieExpire = time()+(60*60*24);//one day -> seconds*minutes*hours
setcookie("CookieName",$cookieValue,$cookieExpire,$cookiePath);

Clearing the cookie:

setcookie("cookieName","", time()-3600, $cookiePath);
unset ($_COOKIE['cookieName']);

Hope that helps.

Solution 7 - Php

If you set the cookie to expire in the past, the browser will remove it. See setcookie() delete example at php.net

Solution 8 - Php

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.

Solution 9 - Php

This is how PHP v7 setcookie() code works when you do:

<?php
    setcookie('user_id','');
    setcookie('session','');
?>

From the output of tcpdump while sniffing on the port 80, the server sends to the client (Browser) the following HTTP headers:

Set-Cookie: user_id=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0
Set-Cookie: session=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0

Observing packets in the following requests the Browser no longer sends these cookies in the headers

Solution 10 - Php

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

setcookie('cookiename', false);

Solution 11 - Php

To delete cookie you just need to set the value to NULL:

"If you've set a cookie with nondefault values for an expiration time, path, or domain, you must provide those same values again when you delete the cookie for the cookie to be deleted properly." Quote from "Learning PHP5" book.

So this code should work(works for me):

Setting the cookie: setcookie('foo', 'bar', time() + 60 * 5);

Deleting the cookie: setcookie('foo', '', time() + 60 * 5);

But i noticed that everybody is setting the expiry date to past, is that necessary, and why?

Solution 12 - Php

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.

Solution 13 - Php

To remove all cookies you could write:

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

Solution 14 - Php

I know that there has been a long time since this topic has been created but I saw a little mistake within this solution (I can call it like that, because it's a detail). I agree that the better solution is probably this solution:

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

But, in the present case, you delete the cookies in every case where the unset function works and immediately you create new expired cookies in case that the unset function doesn't work.

That means that even if the unset function works, it will still have 2 cookies on the computer. The asked goal, in a logical point of view, is to delete the cookies if it is possible and if it really isn't, make it expire; to get "the cleanest" result.

So, I think we better should do:

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

Thanks and have a nice day :)

Solution 15 - Php

Just set the expiration date to one hour ago, if you want to "remove" the cookie, like this:

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

or

setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);

Source: http://www.php.net/manual/en/function.setcookie.php

You should use the filter_input() function for all globals which a visitor can enter/manipulate, like this:

$visitors_ip = filter_input(INPUT_COOKIE, 'id');

You can read more about it here: http://www.php.net/manual/en/function.filter-input.php and here: http://www.w3schools.com/php/func_filter_input.asp

Solution 16 - Php

$cookie_name = "my cookie";
$cookie_value = "my value";
$cookie_new_value = "my new value";

// Create a cookie,
setcookie($cookie_name, $cookie_value , time() + (86400 * 30), "/"); //86400 = 24 hours in seconds

// Get value in a cookie,
$cookie_value = $_COOKIE[$cookie_name];

// Update a cookie,
setcookie($cookie_name, $cookie_new_value , time() + (86400 * 30), "/");

// Delete a cookie,
setcookie($cookie_name, '' , time() - 3600, "/"); //  time() - 3600 means, set the cookie expiration date to the past hour.

Solution 17 - Php

It's simple!

setcookie("cookiename", "cookievalue", 1);

Solution 18 - Php

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");

Solution 19 - Php

You can simply use this customize function:

function unset_cookie($cookie_name) {
	if (isset($_COOKIE[$cookie_name])) {
		unset($_COOKIE[$cookie_name]);
		setcookie($cookie_name, null, -1);
	} else { return false; }
}

If you want to remove $_COOKIE['user_account'].
Just use:

unset_cookie('user_account');

Solution 20 - Php

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

Solution 21 - Php

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

Solution 22 - Php

You have to delete cookies with php in your server and also with js for your browser.. (They has made with php, but cookie files are in the browser client too):

An example:

if ($_GET['action'] == 'exit'){
			// delete cookies with js and then in server with php:
			echo '
			<script type="text/javascript">
				var delete_cookie = function(name) {
					 document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
				};
				delete_cookie("madw");
				delete_cookie("usdw");
			</script>
			';
unset($_COOKIE['cookie_name']);
unset($_COOKIE['cookie_time']);

Solution 23 - Php

Most of you are forgetting that this will only work on a local machine. On a domain you will need a pattern like this example.

setcookie("example_cookie", 'password', time()-3600, "/", $_SERVER['SERVER_NAME']);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsandersView Question on Stackoverflow
Solution 1 - PhpNikunj K.View Answer on Stackoverflow
Solution 2 - PhpRe0slessView Answer on Stackoverflow
Solution 3 - PhpMouloudView Answer on Stackoverflow
Solution 4 - PhpThejoker123View Answer on Stackoverflow
Solution 5 - PhpEric PetroeljeView Answer on Stackoverflow
Solution 6 - Phpuser3285097View Answer on Stackoverflow
Solution 7 - PhpAlistair KnockView Answer on Stackoverflow
Solution 8 - PhpJarret HardieView Answer on Stackoverflow
Solution 9 - PhpNulikView Answer on Stackoverflow
Solution 10 - PhpAmit MerchantView Answer on Stackoverflow
Solution 11 - PhpboksaView Answer on Stackoverflow
Solution 12 - PhpSoumen PasariView Answer on Stackoverflow
Solution 13 - PhpRalphe SamsonView Answer on Stackoverflow
Solution 14 - PhpGregView Answer on Stackoverflow
Solution 15 - PhpJo SmoView Answer on Stackoverflow
Solution 16 - PhpSumudu Sahan WeerasuriyaView Answer on Stackoverflow
Solution 17 - PhpL FView Answer on Stackoverflow
Solution 18 - Php_11oneView Answer on Stackoverflow
Solution 19 - PhpKennyView Answer on Stackoverflow
Solution 20 - PhpAmir FoView Answer on Stackoverflow
Solution 21 - PhpSamuel RamzanView Answer on Stackoverflow
Solution 22 - PhpPoncho_333View Answer on Stackoverflow
Solution 23 - PhpPeter GruppelaarView Answer on Stackoverflow