Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - session lost after refreshing page [duplicate]

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!

like image 303
user43051 Avatar asked Jul 29 '26 11:07

user43051


1 Answers

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';
like image 99
Geseft Avatar answered Aug 01 '26 01:08

Geseft