【问题标题】:Why sometimes the cookie won't be neither unset nor overwrite?为什么有时cookie既不会取消设置也不会覆盖?
【发布时间】:2017-06-30 16:00:45
【问题描述】:

今天我遇到了一个奇怪的问题。我有一段代码有时会在 cookie 中写入一些内容,有时会覆盖它。

当该 cookie 不存在时,我的代码也可以正常工作。我的意思是,当我清除所有浏览器的 cookie 并执行我的代码时,一切都很好。但不知过了多久,那个 cookie 将是不变的、固定的和牢固的。我的意思是它不会再被覆盖,它甚至不会被取消设置。

这是我的代码:(不过一开始也可以正常工作)

.
.
    if( isset( $_GET['u'] ) && ( $_GET['u'] == 'true' || $_GET['u'] == 'false' ) ){
        if( isset($_COOKIE['qanda_unanswered_status']) ) {
            if ( $_COOKIE['qanda_unanswered_status'] != $_GET['u'] ){
                setcookie("qanda_unanswered_status", $_GET['u'], 2147483647);   
            }
        } else {
            setcookie("qanda_unanswered_status", $_GET['u'], 2147483647);   
        }
    }
.
.

    if (isset($_GET['u']) && in_array($_GET['u'], ['true', 'false']) && (!isset($_COOKIE['qanda_unanswered_status']) || $_COOKIE['qanda_unanswered_status'] != $_GET['u']) ) {
        setcookie("qanda_unanswered_status", $_GET['u'], 2147483647);
        $_COOKIE['qanda_unanswered_status'] = $_GET['u'];
    }
.
.

这都是关于 cookie 的。无论如何,你有什么线索,我该如何调试这个问题?什么时候 cookie 将永远不变?我的意思是即使unset($_COOKIE['sth']) 也无法摧毁它。

你对这样的问题有任何线索吗?

【问题讨论】:

    标签: php cookies


    【解决方案1】:

    你不能使用unset()来移除一个cookie,你需要将过期时间设置为过去例如:

    setcookie("qanda_unanswered_status", "", time() - 3600); // one hour ago
    

    然后浏览器上的cookie就会被删除。

    【讨论】:

    • 现在工作正常吗?如果可以,你能接受答案吗,thnx!
    猜你喜欢
    • 2011-01-30
    • 2011-07-25
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 2013-12-21
    • 2014-08-13
    • 1970-01-01
    相关资源
    最近更新 更多