【问题标题】:Incrmenting a Cookies with PHP (Beginner Question)使用 PHP 增加 Cookie(初学者问题)
【发布时间】:2010-04-24 03:28:13
【问题描述】:

我以前使用过会话,但从未使用过 cookie。我想使用 cookie 有两个原因:
1) 学习新东西
2)我想让 cookie 在一个小时左右过期(我知道在代码示例中它会在 40 秒内过期)

我正在尝试编写一个基本的 if 语句,

      if($counter=="1") { //do this second 
} 
        elseif ($counter >="2") { //do this every time after the first and second
} 
        else {// this is the first action as counter is zero
}

这是我用来设置 cookie 的代码:

 // if cookie doesnt exsist, set the default
    if(!isset($_COOKIE["counter_cookie"])) {
        $counter = setcookie("counter_cookie", 0 ,time()+40);

    }

    // increment it
     $counter++;



    // save it
     setcookie("counter_cookie", $counter,time()+40);
     $counter = $_COOKIE["counter_cookie"];

问题是计数器将从 0 设置为 1,但不会从 1 设置为 2,依此类推。任何帮助都会很棒我知道这是一个非常简单的愚蠢问题:|

谢谢!

【问题讨论】:

  • 谁偷了饼干罐里的饼干?
  • 你偷了饼干罐的饼干!

标签: php cookies count conditional setcookie


【解决方案1】:

问题很可能与这一行有关:

$counter = setcookie("counter_cookie", 0 ,time()+40);

您似乎希望 setcookie 返回一个值,但这不会发生。相反,setcookie 只会在成功时返回布尔值 true,在失败时返回 false。

http://php.net/manual/en/function.setcookie.php

您可以尝试这样重写以达到预期的效果:

if(isset($_COOKIE["counter_cookie"]))
{
  $counter = $_COOKIE["counter_cookie"];
}
else
{
  $counter = 0;
}
$counter++
setcookie("counter_cookie", $counter ,time()+40);

【讨论】:

  • 谢谢我通过使用 // 如果没有,设置默认值 if(!isset($_COOKIE["counter_cookie"])) { setcookie("counter_cookie", 0 ,time() +40); } //获取计数器的值 $counter = $_COOKIE["counter_cookie"];
  • 你和我同时编辑它,基本上我的编辑做同样的事情,它只是在设置 cookie 后获取它的值。然后添加它。再次感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
  • 2020-01-04
  • 2020-11-23
  • 2015-03-16
相关资源
最近更新 更多