dongxieting9623 2013-11-16 07:29
浏览 47
已采纳

$ _COOKIE无法获取更新的cookie值

Consider the following code snippet-

    if(some_condition){
        echo $candidate_id= $row_id['id'];
        setcookie("candidate_id", $candidate_id, time()+3600);
        echo "<script>console.log(document.cookie)</script>";
    }
    if(isset($_COOKIE['candidate_id'])){
        echo "from cookie";
        echo $candidate_id= $_COOKIE['candidate_id'];exit;  
    }
    else{
        echo "not from cookie";
        echo $candidate_id= $row_id['id'];exit;
    }

First time it gives a correct output-

 288not from cookie288

and in console,

candidate_id=288; PHPSESSID=kfpjvl9j4rluh1stjdjcijgi75 

But if i again run the code again,i get the following outputs

289from cookie288

and in console,

candidate_id=289; PHPSESSID=kfpjvl9j4rluh1stjdjcijgi75 

This means,on the second run,the cookie value is being modified but $_COOKIE['candidate_id'] is not fetching the updated value. But why?

  • 写回答

1条回答 默认 最新

  • dragonsun2005 2013-11-16 07:57
    关注

    $_COOKIE is initialized based on the cookies in the user's request. It is not updated by calls to setcookie().

    You could fake it by doing something like this:

    function mySetCookie($name, $value, $time) {
        setcookie($name, $value, $time);
        $_COOKIE[$name] = $value;
    }
    

    Then call mySetCookie() wherever you would have called setcookie(). This is possibly buggy, though -- I haven't tested it and am fairly certain it would run into problems in some configurations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 elmos eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私