简体   繁体   中英

PHP Session variable lost after refresh / redirect

I am making login page and everything works fine, but while refreshing secure page or redirecting to another page variable disappears.

Login:

<?php session_start(); 

//connection to database and other stuff

if ($user == $dbuser && $pass == $dbpass) {

    $_SESSION['user'] = $user;
    $_SESSION['authenticated'] = "yes";
    $suser = $_SESSION['user']; //just to test if session works

}

?>

Secure page:

<?php session_start(); ?>

//small amount of html here

<?php
    $suser = $_SESSION['user'];
    $sauth = $_SESSION['authenticated'];

    if ($sauth != 'yes') { //not completed yet (needs user name check)
        echo "<a href='./'>Log in</a> first!";
        require ('./login.php');
        die;
    } else {
    //not so important code here
    }
?>

//rest of html here

I didn't notice any mistakes and error log file is clean so it must be something else. Session works fine after redirecting to secure page but as I said earlier refresh of page or another redirect clears session variables.

Page: http://nano.filiparag.com/admin/ If you want to test it just ask for username and password

Note:
Now I tried doing this with setcookie() and it didn't work again


Solved

The problem was in logout button. I made separate PHP file for it and now everything works fine.

I think you can try using this

Login:

<?php session_start(); 
ob_start();
//connection to database and other stuff

if ($user == $dbuser && $pass == $dbpass) {

    $_SESSION['user'] = $user;
    $_SESSION['authenticated'] = "yes";
    $suser = $_SESSION['user']; //just to test if session works

}

?>

Secure page:

<?php session_start(); 
  ob_start();?>

//small amount of html here
<?php session_start(); ob_start();
    $suser = $_SESSION['user'];
    $sauth = $_SESSION['authenticated'];

    if ($sauth != 'yes') { //not completed yet (needs user name check)
        echo "<a href='./'>Log in</a> first!";
        require ('./login.php');
        die;
    } else {
    //not so important code here
    }
?>

//rest of html here

Im guessing that your login.php scripts is doing something with the session variables when you include it. Can I have a look at your login.php script and I'll edit my answer then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM