doutizong8099 2010-04-24 03:28
浏览 22
已采纳

使用PHP增加Cookie(初学者问题)

I have used sessions before but never cookies. I would like to use cookies for two reasons:
1) it's something new to learn
2) I would like to have the cookie expire in an hour or so (i know in the code example it expires in 40 sec)

I am trying to write a basic if statement that

      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
}

Here is the code I'm using to set the 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"];

The problem is that the counter will be set from 0 to 1 but won't be set from 1 to 2 and so on. Any help would be great I know this is a really simple stupid question :|

Thanks!

  • 写回答

1条回答 默认 最新

  • doujunchi1238 2010-04-24 03:34
    关注

    The problem is most likely related to this line:

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

    It appears you are expecting setcookie to return a value, but that isn't going to happen. Instead, setcookie will simply return a boolean true on success and false on failure.

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

    You could try rewriting it like this to achieve the desired effect:

    if(isset($_COOKIE["counter_cookie"]))
    {
      $counter = $_COOKIE["counter_cookie"];
    }
    else
    {
      $counter = 0;
    }
    $counter++
    setcookie("counter_cookie", $counter ,time()+40);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM