未设置Cookie或第一次无法使用 [英] Cookie not setted or not working the first time

查看:86
本文介绍了未设置Cookie或第一次无法使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在每个页面上,我都设置一个cookie来为与该会话相对应的标题按钮着色. 问题在于,当我第一次在其他部分打开页面时,cookie仍然是旧的,而彩色按钮也是如此. 然后,如果我再次单击相同的按钮,则cookie设置正确.为什么?

On every page I set a cookie to color the header button corresponding to that session. The problem is that the first time I open a page in a different section, the cookie remains the old, and the colored button too. Then if I click another time the same button, the cookie is correctly setted. Why?

这是我的代码:

<?php
include $_SERVER['PERCORSO_GLOBALS'];

$pagelevel = '1';
require_once ROOT_DIR.'/administrator/flock/session_users.php';

setcookie('lng', 'it');
?>

<head>
    ...
</head>

<body>
<?php
$currentpage = basename(__FILE__);

function colorButtonHeader($section){
    if(isset($_COOKIE['lng'])){
        if($_COOKIE['lng'] == $section){
            echo "buttonon";
        }
    }else{
        echo 'Error';
        die($refresh);
    }
}
?>

<div id="button"> 
  <ul>
    <li><a href=<?=$index_admin?>><span class="<?php colorButtonHeader('home') ?>">HOME</span></a></li>
    <li><a href=<?=$italiano?>><span class="<?php colorButtonHeader('it') ?>">ITALIANO</span></a></li>
    <li><a href=<?=$tedesco?>><span class="<?php colorButtonHeader('de') ?>">DEUTSCH</span></a></li>
    <li><a href=<?=$francese?>><span class="<?php colorButtonHeader('fr') ?>">FRANÇAIS</span></a></li>
  </ul> 
</div> 


?>

<div id="content">

     ...

</div>
</body>
</html>

推荐答案

我找到了这种解决方案,它似乎是改进最快的解决方案:

I find this solution, which seems to be the fastest to improve:

function colorButtonHeader($section){
    if(isset($_COOKIE['lng'])){
        if($_COOKIE['lng'] == $section){
            echo "buttonon";
            setcookie('lng', '', time()-3600);
        }
    }else{
        header("Location: ".$_SERVER["REQUEST_URI"]);
        // header("Location: ".$_SERVER["PHP_SELF"]);

    }
}

每次使用后销毁cookie.因此,在每次加载页面时,cookie都无法使用.这意味着页面将重新加载,但是只有一次,因为这样cookie才可用.将再次使用它并销毁它.

Destroy the cookie each time after using it. So on every page load the cookie is not ready to use. This means the page reload, but only once because then the cookie is avaiable. It will be used and the destroied again.

编辑

如果您通过URL传递参数,则在使用时:

If you pass parameters through the URL, then when you use:

header("Location: ".$_SERVER["PHP_SELF"]);

这些参数正在丢失.所以最好使用:

those parameters are getting lost. So it's better to use:

header("Location: ".$_SERVER["REQUEST_URI"]);

这篇关于未设置Cookie或第一次无法使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆