Php session variable blank

//session_register user

$user = $row[‘user’];
$_SESSION[‘user’] = $user;

//session user, is in index.php

//$user = $_SESSION[‘user’];

Is the variable blank (empty) or is it not set (null)? Have you determined that the code setting the session variable is being executed?

Do you have a session_start(); statement on every page that sets or references a session variable?

Do you have php’s error_reporting set to E_ALL (it should always be this value) and display_errors set to ON, preferably in the php.ini on your system, so that php will help you by reporting and displaying all the errors it detects, such as any with the session_start() statement?

the session variables are blank

<?php

   include("config.php");

   session_start();

   $error='';

   if($_SERVER["REQUEST_METHOD"] == "POST") {

   

      // username and password sent from form textbox

      $email = mysqli_real_escape_string($db,$_POST['email']);

      $pass = mysqli_real_escape_string($db,$_POST['pass']);

     

      $sql = "SELECT * FROM users WHERE email = '$email' and pass = '$pass'";

      $result = mysqli_query($db,$sql);      

      $row = mysqli_num_rows($result);      

      $count = mysqli_num_rows($result);

      //read user from database record

      $sql = "SELECT name, gender, age, user, email, pass FROM users where email='$email'";

      $result = mysqli_query($db,$sql);      

      $row = mysqli_num_rows($result);      

      $count = mysqli_num_rows($result);

      $name= $row['name'];

      $gender= $row['gender'];

      $age= $row['age'];

      $user= $row['user'];

      $email= $row['email'];

      $pass= $row['pass'];

      if($count == 1) {

     

         // session variables of user for chatroom

         $_SESSION['name'] = $name;

         $_SESSION["gender"] = $gender;

         $_SESSION["age"] = $age;

         $_SESSION['user'] = $user;

         $_SESSION['email'] = $email;

         header("location: chatroom.php");

      } else {

         $error = "Your Email or Passwsord is invalid";

      }

   }

?>



//display code
<div class="welcome-container">

    <div class="users" id="users">

       <!-- //welcome message to logged in user -->

         Welcome:

         <?php

         echo $_SESSION['user'];

        ?>

    </div>

    </div>

Don’t start new threads for the same problem. I have merged the threads together.

Unfortunately, you didn’t answer all the questions I asked.

Since the login code redirects to chatroom.php (not index.php that you indicated in the first post) after it has detected if the email address was matched (the result from the query to match the email and password isn’t used), the most likely cause is you don’t have a session_start() statement on the page where the “display code” is at.

You must put a session_start(); statement on every page that sets or references a session variable.

If a page requires a logged in user, you must have program logic on that page to test if the session variable is set, and prevent the restricted code from running if it is not.

Your login code is not actually testing if the password matches what is in the database table, because the result from the first query is not being used. You should also be using php’s password_hash() when storing the password in the registration code and password_verify() in the login code to test if the submitted password matches the stored hash.

You should also be using prepared queries instead of putting data directly into the sql query statement, since it is doubtful that you are setting the character set to match your database table when you are making the database connection, and the mysqli_real_escape_string() calls may be ineffective.

I would also like to make a few suggestions and that is don’t put all the user’s information in session. I would just put the user’s id which should be unique anyways.

Here’s how I do it for my website:

    public function verify_credentials($username, $password): bool
    {
        $sql = "SELECT id, password FROM admins WHERE username =:username LIMIT 1";
        $user = $this->retrieve_credentials($sql, $username);
        if ($user && password_verify($password, $user['password'])) {
            session_regenerate_id(); // prevent session fixation attacks
            $_SESSION['user_id'] = $user['id'];
            return true;
        }

        return false;
    }


    protected function retrieve_credentials(string $sql, string $username): ?array
    {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['username' => $username]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result !== false ? $result : null;
    }

You can also pull that information from the database table using PDO and like suggested use prepared statements.

Here’s just an example of my login.php page:

<?php
// Include the configuration file and autoload file from the composer.
require_once __DIR__ . '/../config/clearwebconfig.php';
require_once "vendor/autoload.php";

// Import the ErrorHandler and Database classes from the PhotoTech namespace.
use clearwebconcepts\{
    ErrorHandler,
    Database,
    LoginRepository as Login
};

// Create an ErrorHandler instance
$errorHandler = new ErrorHandler();
// Set the exception handler to use the ErrorHandler instance
set_exception_handler([$errorHandler, 'handleException']);

// Create a Database instance and establish a connection
$database = new Database();
$pdo = $database->createPDO();
// Create a LoginRepository instance with the database connection
$login = new Login($pdo);
$checkStatus = new Login($pdo);

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect to dashboard if the user is already logged in
if ($login->check_login_token()) {
    header('Location: dashboard.php');
    exit();
}

// Generate a CSRF token if it doesn't exist and store it in the session
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Detect environment
$isLocal = in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']);
$cookieDomain = $isLocal ? '' : DOMAIN;
$cookieSecure = !$isLocal; // Set to true on remote server

// Process the login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if the submitted CSRF token matches the one stored in the session
    if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        // Sanitize the username and password input
        $username = strip_tags($_POST['username']);
        $password = $_POST['password'];

        // Verify the user's credentials
        if ($login->verify_credentials($username, $password)) {
            // Generate a secure login token
            $token = bin2hex(random_bytes(32));
            // Store the login token in the database
            $login->store_token_in_database($_SESSION['user_id'], $token);

            // Set a secure cookie with the login token
            setcookie('login_token', $token, [
                'expires' => strtotime('+6 months'),
                'path' => '/',
                'domain' => $cookieDomain, // Adjusted for environment
                'secure' => $cookieSecure, // Adjusted for environment
                'httponly' => true,
                'samesite' => 'Lax'
            ]);

            // Store the login token in the session
            $_SESSION['login_token'] = $token;

            // Redirect the user to the dashboard
            header('Location: dashboard.php');
            exit;
        } else {
            // Log error message for invalid username or password
            $error = 'Invalid username or password';
            error_log("Login error: " . $error);
        }
    } else {
        // Display an error message
        $error = 'Invalid CSRF token';
        error_log("Login error: " . $error);
        $error = 'An error occurred. Please try again.';
    }
}

// Generate a random nonce value
$nonce = base64_encode(random_bytes(16));

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1.0">
    <title>Login Page</title>
    <link rel="stylesheet" media="all" href="assets/css/stylesheet.css">
</head>
<body class="site">
<?php include 'assets/includes/inc-header-nav.php'; ?>

<main class="main_container" itemprop="mainContentOfPage">
    <form class="login_style" method="post" action="login.php">
        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
        <div class="screenName">
            <label class="text_username" for="username">Username</label>
            <input id="username" class="io_username" type="text" name="username" autocomplete="username" required>
        </div>
        <label class="text_password" for="password">Password</label>
        <input id="password" class="io_password" type="password" name="password" required>
        <div class="submitForm">
            <button class="submitBtn" id="submitForm" type="submit" name="submit" value="login">Login</button>
        </div>
    </form>
    <?php if (isset($error)): ?>
        <p class="error"><?php echo $error; ?></p>
    <?php endif; ?>
</main>

<aside class="sidebar"></aside>
<footer class="colophon" itemprop="footer">
    <p>&copy; <?php echo date("Y") ?> Clear Web Concepts</p>
</footer>
<div id="cookie-banner" class="cookie-banner">
    <p>We use cookies to ensure you get the best experience on our website.
        <a href="/privacy-policy">Learn more</a></p>
    <button id="accept-cookies" class="cookie-button">Accept</button>
    <button id="reject-cookies" class="cookie-button">Reject</button>
</div>
<script src="assets/js/scripts.js"></script>
<script src="assets/js/navigation.js"></script>
</body>
</html>

I store a login token in the session for extra security in case someone guesses a user’s name, though nothing is foolproof. I provided an example to show you how it might be done. Looking at other people’s code helps me understand the process. Even if you create your own style, it aids in coding.

Sponsor our Newsletter | Privacy Policy | Terms of Service