I am creating a site and I'm using sessions to manage the user log in status. When a user logs in, I create a session id for the user like so:
$_SESSION['username'] = "username";
How can I check if a user is logged in, and if so, who it is?
I am creating a site and I'm using sessions to manage the user log in status. When a user logs in, I create a session id for the user like so:
$_SESSION['username'] = "username";
How can I check if a user is logged in, and if so, who it is?
If, after you have authenticated the user you are writing $_SESSION['username']
to the the session superglobal, all you need to do is double check the existance of a session username:
session_start()
if (empty($_SESSION['username'])) {
// user is not logged in
}
Figuring out who is logged in is as simple as checking what username you have stored in the $_SESSION['username']
variable that we checked earlier. If you wanted to save their real name from a database result, or other information, just dump that information into the $_SESSION['data_type']
array as well.
The session variables should automatically expire in 24 minutes (PHP default, I think) of inactivity, in which case you should expect the user to login again. If you want to log the user out immediately, check out session_destroy().