如何删除/取消设置 php 上的 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8341487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:28:49  来源:igfitidea点击:

How to delete/unset a cookie on php?

phpcookiessession-cookiessession-timeout

提问by Someone

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

我想取消设置/删除我现有的 cookie:

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

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

但是 cookie 不能被删除或取消设置。那么什么是问题呢?

回答by Sonal Khunt

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

您只能以这种方式取消设置 cookie 可能 -1 不起作用

try this

尝试这个

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

回答by Tom van der Woerdt

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.

删除 cookie 时,您应确保过期日期已过去,以触发浏览器中的删除机制。

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.

此外,在某些情况下,实际取消设置$_COOKIE['TestCookie']也很有用。

回答by emavens

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

删除 cookie 时,您应确保过期日期已过去。

Delete example:

删除示例:

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

回答by Vovkin

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

如前所述 - 在删除 cookie 时,您应该确保过期日期是过去的。

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

但是您还必须使用相同的路径甚至域来删除,您用于创建 cookie,所以如果像这样创建 cookie

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

to delete this cookie use this code

删除此cookie使用此代码

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

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

并且最好使用过去的特定日期而不是time() - 3600

回答by Dileep Kheni

// MUST provide root path or any particular cookie path

//必须提供根路径或任何特定的 cookie 路径

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

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

回答by user4990100

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