How can I check if a user is logged-in in php?
Logins are not too complicated, but there are some specific pieces that almost all login processes need.
First, make sure you enable the session variable on all pages that require knowledge of logged-in status by putting this at the beginning of those pages:
session_start();
Next, when the user submits their username and password via the login form, you will typically check their username and password by querying a database containing username and password information, such as MySQL. If the database returns a match, you can then set a session variable to contain that fact. You might also want to include other information:
if (match_found_in_database()) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username; // $username coming from the form, such as $_POST['username']
// something like this is optional, of course
}
Then, on the page that depends on logged-in status, put the following (don't forget the session_start()
):
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
Those are the basic components. If you need help with the SQL aspect, there are tutorials-a-plenty around the net.
Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.
If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.
I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.
The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].
Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.
Any page you want to perform session-checks on needs to start with:
session_start();
From there, you check your session array for a variable indicating they are logged in:
if (!$_SESSION["loggedIn"]) redirect_to_login();
Logging them in is nothing more than setting that value:
$_SESSION["loggedIn"] = true;
You need this on all pages before you check for current sessions:
session_start();
Check if $_SESSION["loggedIn"
] (is not) true - If not, redirect them to the login page.
if($_SESSION["loggedIn"] != true){
echo 'not logged in';
header("Location: login.php");
exit;
}