doukuang1897 2013-09-11 07:15
浏览 21
已采纳

php cookie不会重写新值

Good morning,

I've got such problem. I would like to store in cookies language, which user will choose. The value in local variable is still changed, but value in cookie is always the same. Even if I always delete the cookie and then I create it again the value stored in cookie is wrong and my local is good. Here's my code:

<?php
if (isset($_GET['lng'])) {
    $lng = $_GET['lng'];
    if (($lng != "en") && ($lng != "de")) {
        $lng = "en";
    }
} else {
    if(!isset($_COOKIE['lang'])) {
        $lng = "en";
    } else {

        $lng = $_COOKIE['lang'];
    }

}

if(isset($_COOKIE['lang'])) {
    setcookie("lang", $_COOKIE['lang'], time()-10); //here I try to remove cookie and then create another
}
setcookie("lang", $lng, time()+5);
print_r($_COOKIE);
echo $lng;

?>

print_r will allways return me the main language (en), even if in variable $lng there is de. I think, there will be just stupid problem, but I can't fix it. This removing line (which I commented) is there because of problem written on official php site:

Be careful of using the same cookie name in subdirectories. Setting a simple cookie

setcookie("region", $_GET['set_region']);

both in the root / and for instance in this case /admin/ will create 2 cookies with different paths. In reading the cookies back only the first one is read regardless of path.

And I thought I've similar problem. But this didn't fix my problem and even when the cookie after 5 second will expire to cookie is then written again the bad "en" value.

Thank for your answer

  • 写回答

1条回答 默认 最新

  • dongwei3336 2013-09-11 07:49
    关注

    Can you try this, it works for me. I edited the code a bit, sorry for obfuscating it with one line if-statements.

    I also set the cookie time to 1 day so it won't disappear when testing the code.

    And remember, you have to update the page to read the new cookie, it will be one step behind $lng.

    <?php
    
    $allowed = array('en', 'de');
    $chosen = $_GET['lng'] ? $_GET['lng'] : ($_COOKIE['lang'] ? $_COOKIE['lang'] : 'en');
    $lng = in_array($chosen, $allowed) ? $chosen : 'en';
    
    setcookie("lang", $lng, time()+24*60*60, '/');
    
    var_dump($_COOKIE['lang']);
    echo $lng;
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型