【问题标题】:Cookie set to expire on session end cannot be prematurely 'deleted'设置为在会话结束时过期的 Cookie 不能过早“删除”
【发布时间】:2015-03-20 10:41:56
【问题描述】:

我一直在测试 cookie 创建、修改和删除,遇到了一个我似乎无法解释的“怪癖”。

我可以正常创建一个 30 天有效期的 cookie:

setcookie("test_cookie", "test_value", time() + (86400 * 30), "/");

然后我可以轻松地“删除”那个 cookie:

setcookie("test_cookie", "", time() - 3600, "/");

但是,当我创建一个过期时间为0 的 cookie(即,将在浏览器关闭/会话结束时过期)时,怪癖就来了:

setcookie("test_cookie", "test_value", 0, "/");

我现在无法在不关闭浏览器的情况下手动删除该 cookie!将其到期时间设置为过去的时间没有任何作用。什么给了?

我一直用于测试的整个页面,注释掉我不使用的行:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Cookie Test</title>
</head>
<body>
    <?php
    // setcookie("test_cookie", "test_value", time() + (86400 * 30), "/");
    // setcookie("test_cookie", "test_value_updated", time() + (86400 * 30), "/");
    // setcookie("test_cookie", "", time() - 3600, "/");

    // setcookie("test_cookie", "test_value", 0, "/");
    // setcookie("test_cookie", "test_value_updated", 0, "/");
    setcookie("test_cookie", "", time() - 3600, "/");
    print_r($_COOKIE);
    ?>
</body>
</html>

【问题讨论】:

    标签: php cookies


    【解决方案1】:

    要设置 cookie,请执行以下操作:

    setcookie("test_cookie", "test_value", 0, "/");
    

    并删除 cookie:

    setcookie("test_cookie");
    

    setcookie("test_cookie", "test_value", 1, "/");
    

    【讨论】:

    • 只有setcookie("test_cookie"); 似乎实际上删除了cookie(好吧,它清空了它,但它仍然存在)。但是,我现在无法再次更新此 cookie?
    • 如果您需要再次更新 cookie,您只需重新创建即可。
    • 这就是我的想法……但它不起作用?它一直是空的?
    • 尝试做这样的事情:if(empty($_COOKIE["test_cookie"])) { setcookie("test_cookie", "test_value" , time() + 3600, "/"); }
    • 不,它只是呆在那里空白......多么奇怪!
    猜你喜欢
    • 2011-04-13
    • 2016-06-02
    • 2011-07-24
    • 1970-01-01
    • 2011-05-07
    • 2012-05-23
    • 2013-12-26
    • 2013-07-18
    • 1970-01-01
    相关资源
    最近更新 更多