Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 844
Someone Avatar asked Dec 01 '11 12:12

Someone


People also ask

Where are cookies stored in PHP?

Cookies are always stored in the client. The path only sets restrictions to what remote pages can access said cookies. For example, if you set a cookie with the path "/foo/" then only pages in the directory "/foo/" and subdirectories of "/foo/" can read the cookie.

How cookies are created and destroyed in PHP?

Example 1: You can create the cookies by writing setcookie() and entering the expiry date of the cookie. If you want to delete the cookie then set the cookie expiry date to the current time. If you want to display the cookie then you can echo the cookie by $_cookie['name'] and it will print the cookie details.

What is $_ cookie in PHP?

Introduction. The superglobal $_COOKIE stores variables passed to current script along with HTTP request in the form of cookies.


3 Answers

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

try this

setcookie ("user", "", time() - 3600);
like image 182
Sonal Khunt Avatar answered Nov 10 '22 11:11

Sonal Khunt


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);
like image 23
emavens Avatar answered Nov 10 '22 12:11

emavens


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.

like image 45
Tom van der Woerdt Avatar answered Nov 10 '22 11:11

Tom van der Woerdt