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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)