douzhai1182 2014-10-27 15:47
浏览 138
已采纳

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 15: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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?