Search code examples
phpsessioncookiesisset

Cookie not setted or not working the first time


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>

Solution

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