11

是否可以通过 JS 和 PHP 删除前面设置的 cookie?

我正在这样做:

*前(JS):

if ($.cookie('myCookie'))
{
   console.log('Cookie.. :(  ');
}
else
{
    console.log('Yaay! No cookie!');
    $.cookie('myCookie', '123');
}

返回(PHP):

if (isset($_REQUEST['removeCookie']))
{
   setcookie("myCookie", "", time()-3600);
   unset($_COOKIE['myCookie']);
}

结果:

在此处输入图像描述

好像是个谜

4

5 回答 5

10

You can't force the browser to delete the cookie file. You can, however, delete the contents of the cookie and expire it. Which is exactly what you're doing with your code above. I would probably tweak it slightly:

setcookie('myCookie', '', 1, '/'); // no need to calculate one hour ago.
于 2013-03-06T16:19:40.303 回答
4

如果客户端时间错误,使用 time() 函数设置 cookie 过期可能无法按预期工作。

要取消设置 cookie 尝试,

setcookie('myCookie', 'blah blah', 1);

来源:php setcookie 文档中的评论

于 2013-03-06T16:21:20.657 回答
2

这将取决于用户 PC 在超时后删除 cookie。就个人而言,我不会相信这一点。我会将 cookie 设置为空值,或者DELETED在您的测试代码中将其设置为 then 检查它是否已设置,然后检查该值是否为空DELETED

于 2013-03-06T16:17:32.990 回答
1

要通过 PHP 从浏览器中完全删除 cookie,试试这个代码

$name = 'exists_cookie';
unset($_COOKIE[$name]);
  // Set empty value
$blank = setcookie($name, '', time() - 3600);
于 2014-09-05T23:03:51.887 回答
0

有人可以在测试机器上运行此代码吗?我有点困惑,为什么 cookie 可以“取消设置”但不能在 php 中更改值或过期等,似乎 setcookie() 根本不起作用。

<script type="text/javascript" src="jquery.js"></script>
<script src="jquery.cookie.js"></script>
<script>
   $.cookie('myCookie', '123' ,'/');
   console.log("Created myCookie");
</script>
<?php
   echo $_COOKIE['myCookie'];
   //Comment/uncomment below as required
   //setcookie("myCookie", "BLAH", time()-430000);
   //$_COOKIE['myCookie'] = "BLAH";
   setcookie('myCookie', '', 1, '/');
   echo "<br />unset myCookie";
   echo "<br />".$_COOKIE['myCookie'];
?>
<script>
console.log($.cookie('myCookie').length);
if ($.cookie('myCookie').length>0)
{
   console.log('Cookie exists  ');
   console.log($.cookie('myCookie'));
}
else
{
    console.log('Yaay! No cookie!');
}
</script>

您似乎能够创建一个 php <> JS cookie mismatch 即:2 个 cookie 调用完全相同但存储不同的数据。

于 2013-03-06T16:13:39.827 回答