douzhai1182 2014-10-27 07:47
浏览 140
已采纳

setcookie()在第一次访问页面时将$ _COOKIE设置为零[重复]

This question already has an answer here:

I have this code in a php page:

if(!isset($_COOKIE[$cookie_name])) {
    if(!setcookie($cookie_name, mt_rand(), time() + (86400 * 30), "/")) {
        die("[ERROR COOKIE] Failed to set cookie!");
    }
}

If I don't have any cookie set in my browser the first time the page is loaded $_COOKIE[$cookie_name] is set to 0. Afterwards, if I reload the page, it is set to a random number as expected.

So far I just make a workaround like this:

if(!isset($_COOKIE[$cookie_name])) {
    if(!setcookie($cookie_name, mt_rand(), time() + (86400 * 30), "/")) {
        die("[ERROR COOKIE] Failed to set cookie!");
    }
    if($_COOKIE[$cookie_name] == 0) {
        echo "<meta http-equiv=\"refresh\" content=\"0; url=./\" />";
        die();
    }
}

but what I'd like to understand is why the first time setcookie() defaults to 0.

</div>
  • 写回答

1条回答 默认 最新

  • dpjs2005 2014-10-27 07:50
    关注

    It doesn't. It defaults to NULL, because it hasn't been set.

    setcookie merely adds the Set-Cookie header to the list of headers to be sent to the browser. It is a convenience shortcut for header("Set-Cookie: ..."); that does the formatting for you. It does not modify the $_COOKIE superglobal.

    You can, of course, do it yourself:

    function updatecookie($name,$val,$exp=0,$path="/",$domain="",$secure=false,$httponly=false) {
        $ret = setcookie($name,$val,$exp,$path,$domain,$secure,$httponly);
        if( $ret) $_COOKIE[$name] = $val;
        return $ret;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部