Cookie not setted or not working the first time

半城伤御伤魂 提交于 2021-02-17 06:49:06

问题


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?

Here my code:

<?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>

回答1:


Read the documentation:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.

When you use setcookie(), you're setting a cookie, but the $_COOKIE array contains only existing cookies (it's created on the page load).

Do this instead:

setcookie('lng', 'it');
$_COOKIE["lng"] = "it";

or simply redirect to a page itself (header("Location: ".$_SERVER["PHP_SELF"]);) when the cookie is set for the first time.




回答2:


Just simply reload the page each time You set Your cookies.

 setcookie("Cookiename", $value, time()+1800, "/", $_SERVER['SERVER_NAME'], FALSE, TRUE);
 header('Location:'.$_SERVER['REQUEST_URI']);



回答3:


Cookie is set in client machine so you cannot set and check simultaneously from server,use JavaScript instead.

you can use this js function Taken from this post

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
       if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
  return null;
}

function colorButtonHeader(selected){
   if(readCookie('lng') == selected ){
         alert('cookie is set ');
     }else{
           alert('Wrong language');
        }
}



回答4:


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"]);

    }
}

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.

EDIT

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"]);


来源:https://stackoverflow.com/questions/16896880/cookie-not-setted-or-not-working-the-first-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!