php - session lost after refreshing page

15,142

Solution 1

First of all, no need for javascript to redirect you to the index page. You can do it from PHP too:

header("Location: index.php");

So the login.php will look like this:

if ($loginNumRows == 1) {
   session_start();
   $_SESSION['username'] = $loginRow['name'];
   header("Location: index.php");

Note, that I have changed the order. As others I strongly recommend to put session start above all of your code.

And finally make sure that you have session started in the index.php file too(this should be also placed above all of your code ):

session_start();

EDIT: If you want to stick with your javascript method ( witch I highly not recommend ), than your login.php code should look like this:

if ($loginNumRows == 1) {
   session_start();
   $_SESSION['username'] = $loginRow['name'];
   echo 'true';

Solution 2

Make sure that you have session_start(); at the top of all your scripts.

Solution 3

As previously stated above, I would first put session_start() above all other code on the page, not in the conditional statement.

Share:
15,142
user43051
Author by

user43051

Updated on June 23, 2022

Comments

  • user43051
    user43051 almost 2 years

    So I am developing a login system for my website and I would like to change the navigation bar when the user is logged but I can't get it to work because the session keeps getting lost after I refresh the page to update the navigation bar. This is what I got in my login.php script:

    if ($loginNumRows == 1) {
       echo 'true';
       session_start();
       $_SESSION['username'] = $loginRow['name'];
    

    When this echoes 'true', the following javascript is loaded:

    if (html == 'true') {
        window.location.href = "index.php";
    

    I tried with "location.reload(true);" and it is still the same. And in the main page, where the navigation bar is, I make the following check:

    <?php if (isset($_SESSION))
                {...}
    

    However this always returns false. Any ideas what to do? Thanks!