Search code examples
phpsessionvariables

php session variables on multiple pages not working


<?php
//page 1
session_start();
// codes...
$_SESSION['user_name_loggedin'] = $user;
header("Location: profile.php");
// codes...
?>
<?php
//page2
session_start();
// codes...
if(isset($_SESSION['user_name_loggedin'])){
    echo $_SESSION['user_name_loggedin'];
}else{
    echo 'not set<br>';
}
// codes...
?>

I am trying to get a login working on my site using sessions. Above shows examples of the two pages I wish to transfer information between using a session. $user is taken from the login form on the login page. On the profile page, after logging in, it only shows 'not set'. Is there anything I am missing?

Thanks in advance


Solution

  • Tried it locally using the following code:

    1 test.php

    `<?php
    //page 1
    session_start();
    $user="dvjnvki";
    $_SESSION['user_name_loggedin'] = $user;
    header("Location: b.php");
    ?>`
    

    2 b.php

    <?php
    //page2
    session_start();
    if(isset($_SESSION['user_name_loggedin'])){
    echo $_SESSION['user_name_loggedin'];
    }else{
    echo 'not set<br>';
    }
    ?>
    

    and it does work perfectly. So the issue with your code might be that you might not be getting a value for the variable called $user. Try to echo that first and see if you get an output.