How to echo a logged in user from a session

Hi All

I’ve created the login system and all is good, however i’m trying to echo the logged in users name in the header with no joy. I’ve tried multiple different ways from various sites around google but i can’t seem to get it functioning. Please can someone take a look and let me know where i’m going wrong…

<?php
//Login Page

// Initialize the session
session_start();
 
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    if ($_SESSION["user_level"]==99){ 
            header("location: admin/index.php");
            exit;
    }
    else {
        header("location: dealer/index.php");
        exit;
    }
}
 
// Include config file
require_once "includes/db_conn.php";
 
// Define variables and initialize with empty values
$email = $password = "";
$email_err = $password_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Check if username is empty
    if(empty(trim($_POST["email"]))){
        $email_err = "Please enter email.";
    } else{
        $email = trim($_POST["email"]);
    }
    
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate credentials
    if(empty($email_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, fname, user_level, email, password FROM dealerenq WHERE email = ? AND status = 'Approved'";
        
        if($stmt = $con->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("s", $param_email);
            
            // Set parameters
            $param_email = $email;
            
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Store result
                $stmt->store_result();
                
                // Check if username exists, if yes then verify password
                if($stmt->num_rows == 1){                    
                    // Bind result variables
                    $stmt->bind_result($user_id, $userlevel, $fname, $email, $hashed_password);
                    if($stmt->fetch()){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            
                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["user_id"] = $user_id;
                            $_SESSION["email"] = $email;
                            $_SESSION["user_level"] = $userlevel;
                            $_SESSION["fname"] = $fname;
                            
                            if ($_SESSION["user_level"]!= 99){ 
                                header("location: dealer/index.php");
                                exit;
                        }
                        else if ($_SESSION["user_level"] == 99){
                            header("location: /admin/index.php");
                            exit;}
                    
                        } else{
                            // Display an error message if password is not valid
                            $password_err = "The password you entered was not valid.";
                        }
                    }
                } else{
                    // Display an error message if username doesn't exist
                    $email_err = "No account found with that email or account awaiting approval.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
        
        // Close statement
        $stmt->close();
    }
    
    // Close connection
    $con->close();
}
?>

On the following page, please can you suggest how i would correctly call the session variable for $fname and echo this out elsewhere on the page.

<?php
// In header of dealer page //

// Initialize the session
session_start();
 
// Check if the user is logged in, if not then redirect him to login page
if(isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] == true){

        if ($_SESSION["user_level"] == 99){ 
            header("location: /admin/index.php");
            exit;
        }
        else if ($_SESSION["user_level"] == 1){
            //user authenticated - ok to show page
        }

}
else {
    header("location: /login.php?msg=ok&err=not_logged_in");
    exit;
}
?>

Thanks in advance all.

As simple as:-

echo htmlspecialchars($_SESSION["fname"]);
1 Like

Thanks Sam, unfortunately its not echoing onto the page. Should i call the session variable at the top of each page? and then echo it further down or is it that it would have been bound to the session variable on the login page?

var_dump() the session to see if it’s what you think it should be.

Interestingly. its firing out everything but its got null as the name [“fname”]=> NULL

So fname is in the session, but it is NULL. :thinking:
Check the table?

It’s in the table for sure. Have I declared it correctly on my login page?

No, I don’t think so, but I’m not familiar with mysqli.

Compare

$sql = "SELECT id, fname, user_level, email, password FROM dealerenq 
        WHERE email = ? AND status = 'Approved'";

with

$stmt->bind_result($user_id, $userlevel, $fname, $email, $hashed_password);
2 Likes

This is where the problem is, and points out a big issue with the mysqli extension. The prepared query interface is overly complicated and completely different from the non-prepared query interface. If you are open to switching to the PDO extension, most of the php database statements you have now will go away, you will be able to use the same sql query syntax that you have now, and will be able to fetch data directly from a select query. With the PDO extension, you won’t have to repeat the list of columns/variables to fetch the data, because you can simply fetch the row from the result set into a php variable, like you are used to doing for non-prepared queries.

There’s also an operational problem with storing user related information in session variables when the user logs in. If you need to edit/change any of the values, such as the user_level, or banning someone (please mr. spammer, log out and log in so you will get banned :shifty: ), the change will only take effect if someone logs in again. You should only store the user id in a session variable, to indicate who the logged in user is, then query on each page request to get any related user data.

Yes, all that binding parameters and then binding results seems very verbose to me. And as shown here, more code means more places to make an error, then more places to have to look to find the error.
With PDO you can just fetch that data directly into a “user” object or something like (having first created a user class or whatever you find appropriate).

Thanks Droopsnoot. I’ve double checked and it all matches up.

If i do a var dump all of the info now correctly is displayed.

Please can you confirm where i’m going wrong on this echo. I’m trying to assign a variable to the user_id session and call that variable so that i can input it into a form.

<?php $user_id = $_SESSION["user_id"]; ?>
<?php echo $user_id; ?>

Scrap that, cracked it now. Cheers gents

Dont create variables for nothing and dont open and close Php for nothing. That entire code should simply be

<?= $_SESSION["user_id"] ?>
1 Like

Well thats whole lot cleaner and quicker. Thanks benanamen :ok_hand::+1:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.