PHP: Get username from session
Solution 1
You have to store the username in the session for it to be available on another page load, currently the script only stores these values in the session;
$_SESSION['loggedin'] = $row[$this->pass_column];
$_SESSION['userlevel'] = $row[$this->user_level];
What you have to do is add the $username
to the session that is passed into the login
function, like below;
$_SESSION['username'] = $username;
The username will now be stored in the session with the key username.
To be able to use it on another page, make sure that before attempting to use it you initiate the session by calling the function session_start()
.
Solution 2
Basically, just write it inside like
session_start();
echo $_SESSION['username'];
or
echo $_SESSION['password'];
A brief explanation of how sessions work.
first you start the session and assign any value to a session ex:
session_start();
$_SESSION['username'] = 'john';
then echoing works like:
echo $_SESSION['username']; // will echo out 'jonh'
note session_start()
must be shared in-between the pages you want to use the session
PatricF
Updated on June 02, 2020Comments
-
PatricF almost 4 years
I'm not very good at PHP and I have a little problem. I've been playing around with this script.
And I can't for the life of me figure out how to echo the username of a logged in user. I tried to print all the information of the session like this:
var_dump($_SESSION)
but I just got the hashed password and the userlevel int.
Can someone maybe help me here? I just want to be able to echo the username.
-
Barmar almost 11 yearsThe script you linked to does't save the username in as a session variable. If you want that, you have to add it.
-
-
samayo almost 11 yearsIt it does not give you anything, the you have not assigned a session yet
-
PatricF almost 11 yearsYes I have that on top. I get the information from the session, there's just no information on the username..
-
halfer almost 11 years@PatricF: when responding to answers, you need to give them something to work with. For example, you could link to an external copy of your script as it now stands. Otherwise, how is this answerer meant to respond?
-
Nathan van der Werf almost 11 yearsso if you do the following: session_start(); $_SESSION['username'] = 'Test'; echo $_SESSION['username']; it will return nothing ?
-
PatricF almost 11 yearsWow, that was a really fast answer. This worked perfectly! Thank you very much.
-
GriffLab almost 11 years@PatricF No problem if it helped you consider accepting the answer as it will help others in the future