Home > Software engineering >  Session variable is set true but appears false or non-existent on next page
Session variable is set true but appears false or non-existent on next page

Time:10-24

If a user is logged in $_SESSION['user_active'] = true; but after logging in the session actually returns false (or does not exist at all). Any help is very much appreciated. Does anybody have any idea what's going wrong?

EDIT 1: it works if I remove everything related to $_SESSION['user_active']

EDIT 2: added session_start() to login.class.php as well, but no improvement.

The HTML form is processed by login.class.php :

      <form id="loginForm" class="form" action="acc/login.class.php" method="POST">
        <div class="form-group">
          <label for="loginUsername" class="form-label">Username</label>
          <input id="loginUsername" class="form-control" type="text" name="username" placeholder="Username"><br> <!-- Username -->
        </div>
        <div class="form-group">
          <label for="loginPassword" class="form-label">Password</label>
          <input id="loginPassword" class="form-control" type="password" name="password" placeholder="Password"> <!-- Password -->
          <div class="form-text"><p>&nbsp;</p></div>
        </div>
        <div class="form-group">
          <button id="loginSendform" class="btn btn-primary" type="submit">
            Inloggen
            <span class="bi-lock-fill"></span>
            <span class="bi-unlock-fill"></span>
          </button>
        </div>
      </form>

Within login.class.php the session should return 'true':

<?php

  session_start();
  
  // Required files
  require_once( $_SERVER['DOCUMENT_ROOT'] . '/app/config.php' );
  require_once( DIR_ROOT . '/system/db/database.class.php' );
  require_once( DIR_ROOT . '/system/db/queries.class.php' );

  class Login extends Queries {
    // Queries extends database

    public function userLogin($postForm) {

      // Validate user data
      if (isset($postForm['username']) && !empty($postForm['username'])) { # Username
        $username = filter_var($postForm['username'], FILTER_SANITIZE_STRING);
      } else {
        $username = null;
      }
      if (isset($postForm['password']) && !empty($postForm['password'])) { # Password
        $password = md5($postForm['password']);
      } else {
        $password = null;
      }
      
      // Process login
      $login = "SELECT * FROM users WHERE username='$username' AND userpass='$password'";
      $result = mysqli_query($this->con, $login)
        or die (mysqli_connect_errno()."Could not connect to database");

      // Convert to array
      while ($row = mysqli_fetch_assoc($result)) {
        $array[] = $row;
      }
      $rows = $result->num_rows;
        
      // Check if user exists
      if ($rows == 1) {
        $_SESSION['user_active'] = true;
        $_SESSION['firstname'] = $row['firstname'];
        header('location: ../calendar.php');
      } else {
        $_SESSION['user_active'] = false;
        // Store error
        $_SESSION['register_error'] = "Username or password is incorrect";
        header('location: ../login.php');
      }

    }

    // Logout user
    public function userLogout() {
      $_SESSION['user_active'] = false;
    }
    
  } # End class

  $newLogin = new Login;
  $newLogin->userLogin($_POST);

If login is successful: redirect to calendar.php which has this on top:

<?php
  session_start();

  // If login or register login is succesful: Clean up session variables
  unset($_SERVER['register_error'], $_SERVER['register_success']);

  if (isset($_SERVER['user_active']) && $_SERVER['user_active'] == true) {
    echo "Success"; return false; # Logged in
  } else {
    echo "Error"; return false; # Not logged in
  }

  $filename = "calendar";
  $pagename = "Welcome";

  require_once( '../config.php' );
  require_once( DIR_ROOT . '/system/com/header.inc.php' );
  require_once( DIR_ROOT . '/user/com/sidebar.inc.php');
?>

config.php only contains some define() statements.

This next page keeps returning echo "Error"; instead of echo "Success"; so the login session variable is either not true or it does not even exist. The login page and the next page are the only ones using this variable for now. Why does this not work?

CodePudding user response:

You need to start session in the login.class.php file as well.

add session_start(); at the top of your login.class.php file.

I see now. Include the session_start(); at the top of login.class.php file, and

the problem is within

if (isset($_SERVER['user_active']) && $_SERVER['user_active'] == true) {
    echo "Success"; return false; # Logged in
  } else {
    echo "Error"; return false; # Not logged in
  }

You see you use $_SERVER['user_active'], it should be $_SESSION['user_active']

You need to use $_SESSION to access session variables. $_SERVER is something else

  • Related