dongxieting9623 2013-11-15 23: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-15 23: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部