0

我以前使用过会话,但从未使用过 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,依此类推。任何帮助都会很棒我知道这是一个非常简单的愚蠢问题:|

谢谢!

4

1 回答 1

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);
于 2010-04-24T03:34:13.657 回答