How to check if a user is logged in using php

02nd, January 2018 By

To check if user is logged in or not you need to do the follow the stepes given and see the example that will help to check whether the user is logged in or not.

Step 1

Create session of username based on the user information filled in the login form but it should match with the database enteries . For example :

<?php
$sql = "select * from users where username='" . $_POST['adminUser'] . "' and password='" . $_POST['adminPassword'] . "' and status = 'A'";
$resuls = mysql_query($sql);
$numRows = mysql_num_rows($resuls);
if ($numRows > 0) {
 $row = mysql_fetch_assoc($resuls);
 session_start();
 $_SESSION['username'] = $row['username'];
 $_SESSION['id'] = $row['id'];
}
?>

Here you can see that we have made a session of username based on the information matched from the users table and post from the login form.

Step 2

Check if the session is set or not to redirect a particular page . If that username session is not set it means user is not logged in For example:

<?php
if (!isset($_SESSION['username'])) {
 @header("Location: logIn.php");
 exit(0);
} else {
 header("Location: index.php");
}
?>

Here you can see that we checked username session is set or not based on that we redirect to index page if not then it will redirect to login page.

Leave a Reply

Your email address will not be published. Required fields are marked *