Someone
Someone

Reputation: 736

How to delete/unset a cookie on php?

I want to unset/delete my existing cookie with this:

setcookie ("user", "", time()-1); 
unset($user);

But cookies can not be deleted or unset. So what is problem?

Upvotes: 14

Views: 51924

Answers (7)

P GS
P GS

Reputation: 21

Nothing on this page is correct except the code where the cookie path is included. The cookies are not removed unless a path is specified.

Upvotes: 0

user4990100
user4990100

Reputation: 31

setcookie ("user", "", time() - 3600);
//will reset cookie(client,browser)
unset($_COOKIE["user"]);
// will destroy cookie(server)

Upvotes: 3

Vovkin
Vovkin

Reputation: 491

As already was said - when deleting a cookie you should assure that the expiration date is in the past.

BUT you also have to use the same path and even domain for deleting, which you used for cookie creating, so if create cookie like this

setcookie ("user", "John", time()+7200, '/', 'mydomain.com'); 

to delete this cookie use this code

setcookie ("user", "", time()-3600, '/', 'mydomain.com');

and also better use specific date in the past instead of time() - 3600

Upvotes: 3

Dileep Kheni
Dileep Kheni

Reputation: 882

// MUST provide root path or any particular cookie path

//SET COOKIE
setcookie ("user", "", time() + 3600 , '/'); 

//UNSET COOKIE
setcookie ("user", "", time()-100 , '/' ); // past time

Upvotes: 3

emavens
emavens

Reputation: 41

When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

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

Upvotes: 4

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29965

Nothing - that code looks fine to me.

Quoting the docs:

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser.

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

You may like to specify a time that's more in the past to avoid problems with the computer's time that may be a bit off.

Additionally, in some cases it's useful to actually unset $_COOKIE['TestCookie'] as well.

Upvotes: 3

Sonal Khunt
Sonal Khunt

Reputation: 1894

you can unset cookies this way only may -1 not work

try this

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

Upvotes: 22

Related Questions