Multi User Role Based Login in PHP with MySQL PDO - onlyxcodes

Thursday, 20 December 2018

Multi User Role Based Login in PHP with MySQL PDO

Hi, if you want to manage different role based users are login access in the single login form and go to own account. This tutorial helps you to build Multi User Role Based Login in PHP with MySQL PDO.

The role based user login access nowadays is one of the most popular features of a modern web application.

We can say that these features become part of the school system, you manage two roles, professor and students, you can give restricted permission to each role. Such as the role of the student, they do not access the professor's account while changing their profile photo, mobile number, etc. and more can be personalized to manage depending on the requirement.

OK, let's continue the tutorial and we've built a multi user role based login system with restricted permission to manage different roles.




Multi User Role Based Login in PHP with MySQL PDO

Table Content

1. Where Use Of Multi User Role Based Login System

2. Requirement

3. Database and Table

4. connection.php

5. index.php [ PHP Login Form ]

    5.1 PHP Code For Login Form

    5.2 Login Codes Logic Explanation

6. register.php [ PHP Registration Form ]

    6.1 PHP Code For Registration Form

    6.2 Registration Codes Logic Explanation

7. admin_home.php

8. employee_home.php

9. user_home.php

10. logout.php


1. Where Use Of Multi User Role Based Login System

Imagine the management system of the company. Three admin, user, and employee roles are accessed in a single login form.

Suppose the user's role is to log in successfully and go to the user's account, seeing their attendance, work, task, etc. The same other roles admin and employee use the same form of a login and have their account and work with their account as they need.

This tutorial helps to not create a separate roles login page. Login access functionality in the single login form to easily handle different roles as well as depend on your custom requirement.

2. Requirement

Notepad++ – Download In this editor, I made all the codes of this project.

XAMPP Server – Download I've set up and executed this project on this server.

See the structure of the project directory inside C:\xampp\htdocs location below. Because I have the XAMPP server installed in C: drive. 

Project Directory Structure of Multi User Role Based Login System

I created 7 files below for a multi user role based login system to develop completely.

1. connection.php

2. index.php

3. register.php

4. admin_home.php

5. employee_home.php

6. user_home.php

7. logout.php

3. Database and Table

To create a database and table, import and run below SQL code your PhpMyAdmin.

I have already inserted admin dumping records in a table here. Because this project only uses one super admin.

Note – The column in the table role field indicates the particular name of the role to be added by new users.

--
-- Database: `php_multiplelogin`
--

-- --------------------------------------------------------

--
-- Table structure for table `masterlogin`
--

CREATE TABLE `masterlogin` (
  `id` int(11) NOT NULL,
  `username` varchar(15) NOT NULL,
  `email` varchar(40) NOT NULL,
  `password` varchar(20) NOT NULL,
  `role` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `masterlogin`
--

INSERT INTO `masterlogin` (`id`, `username`, `email`, `password`, `role`) VALUES
(11, 'hamid', '[email protected]', '123456', 'admin');

4. connection.php

I create a database connection in this file by the PDO extension of PHP.

<?php
$db_host="localhost"; //localhost server 
$db_user="root"; //database username
$db_password=""; //database password   
$db_name="php_multiplelogin"; //database name

try
{
 $db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
 $e->getMessage();
}

?>

5. index.php [ PHP Login Form ]

I create a login form in this file with two input boxes and one select option. The input box that takes email and password, a select option that contains the role name admin, user, and employee which selects login access by specific role.

<form method="post" class="form-horizontal">
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Email</label>
 <div class="col-sm-6">
 <input type="text" name="txt_email" class="form-control" placeholder="enter email" />
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Password</label>
 <div class="col-sm-6">
 <input type="password" name="txt_password" class="form-control" placeholder="enter passowrd" />
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Select Type</label>
 <div class="col-sm-6">
  <select class="form-control" name="txt_role">
   <option value="" selected="selected"> - select role - </option>
   <option value="admin">Admin</option>
   <option value="employee">Employee</option>
   <option value="user">User</option>
  </select>
 </div>
 </div>
    
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 <input type="submit" name="btn_login" class="btn btn-success" value="Login">
 </div>
 </div>
    
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 You don't have a account register here? <a href="register.php"><p class="text-info">Register Account</p></a>  
 </div>
 </div>
     
</form>

PHP Login Form Visually Below This Type :


PHP Login Form . Multi User Role Based Login in PHP with MySQL PDO

5.1 PHP Code for Login Form


Below PHP login codes responsible for identifying the user's authenticated email, password, and role name according to the specific role selection and verifying in the database. 

if all details are present in the table then the session will start according to the specific role name selection and roles will allow access to the own dashboard. otherwise, the required message will be displayed.

I know lengthy but not hard move to logic code explanation below, you'll comprehend the full logic of the codes.

<?php
require_once 'connection.php';

session_start();

if(isset($_SESSION["admin_login"])) //check condition admin login not direct back to index.php page
{
 header("location: admin/admin_home.php"); 
}
if(isset($_SESSION["employee_login"])) //check condition employee login not direct back to index.php page
{
 header("location: employee/employee_home.php"); 
}
if(isset($_SESSION["user_login"])) //check condition user login not direct back to index.php page
{
 header("location: user/user_home.php");
}

if(isset($_REQUEST['btn_login'])) //login button name is "btn_login" and set this
{
 $email  =$_REQUEST["txt_email"]; //textbox name "txt_email"
 $password =$_REQUEST["txt_password"]; //textbox name "txt_password"
 $role  =$_REQUEST["txt_role"];  //select option name "txt_role"
  
 if(empty($email)){      
  $errorMsg[]="please enter email"; //check email textbox not empty or null
 }
 else if(empty($password)){
  $errorMsg[]="please enter password"; //check passowrd textbox not empty or null
 }
 else if(empty($role)){
  $errorMsg[]="please select role"; //check select option not empty or null
 }
 else if($email AND $password AND $role)
 {
  try
  {
   $select_stmt=$db->prepare("SELECT email,password,role FROM masterlogin
          WHERE
          email=:uemail AND password=:upassword AND role=:urole"); //sql select query
   $select_stmt->bindParam(":uemail",$email);
   $select_stmt->bindParam(":upassword",$password); //bind all parameter
   $select_stmt->bindParam(":urole",$role);
   $select_stmt->execute(); //execute query
     
   while($row=$select_stmt->fetch(PDO::FETCH_ASSOC)) //fetch record from MySQL database
   {
    $dbemail =$row["email"];
    $dbpassword =$row["password"];  //fetchable record store new variable they are "$dbemail","$dbpassword","$dbrole"
    $dbrole  =$row["role"];
   }
   if($email!=null AND $password!=null AND $role!=null) //check taken fields not null after countinue
   {
    if($select_stmt->rowCount()>0) //check row greater than "0" after continue
    {
     if($email==$dbemail AND $password==$dbpassword AND $role==$dbrole) //check type textbox email,password,role and fetchable record new variables are true after continue
     {
      switch($dbrole)  //role base user login start
      {
       case "admin":
        $_SESSION["admin_login"]=$email;   //session name is "admin_login" and store in "$email" variable
        $loginMsg="Admin... Successfully Login..."; //admin login success message
        header("refresh:3;admin/admin_home.php"); //refresh 3 second after redirect to "admin_home.php" page
        break;
        
       case "employee":
        $_SESSION["employee_login"]=$email;    //session name is "employee_login" and store in "$email" variable
        $loginMsg="Employee... Successfully Login...";  //employee login success message
        header("refresh:3;employee/employee_home.php"); //refresh 3 second after redirect to "employee_home.php" page
        break;
        
       case "user":
        $_SESSION["user_login"]=$email;    //session name is "user_login" and store in "$email" variable
        $loginMsg="User... Successfully Login..."; //user login success message
        header("refresh:3;user/user_home.php");  //refresh 3 second after redirect to "user_home.php" page
        break;
        
       default:
        $errorMsg[]="wrong email or password or role";
      }
     }
     else
     {
      $errorMsg[]="wrong email or password or role";
     }
    }
    else
    {
     $errorMsg[]="wrong email or password or role";
    }
   }
   else
   {
    $errorMsg[]="wrong email or password or role";
   }
  }
  catch(PDOException $e)
  {
   $e->getMessage();
  }  
 }
 else
 {
  $errorMsg[]="wrong email or password or role";
 }
}
?>

5.2 Login Codes Logic Explanation


Row no 2 – Include the configuration file of the database using the function require_once. Because we fire SQL select query for user login through $db database object.

Row no 4 – Using session_start() function we start the session.

Row no 6 to 17 – Three if conditions, get different roles name session keys (admin_login, employee_login, user_login). If both are found then the function header() sends the roles specific account.

This is the main objective of the session as the active login of any user will not directly access the login page their account required logout.

if(isset($_SESSION["admin_login"])) //check condition admin login not direct back to index.php page
{
 header("location: admin/admin_home.php"); 
}
if(isset($_SESSION["employee_login"])) //check condition employee login not direct back to index.php page
{
 header("location: employee/employee_home.php"); 
}
if(isset($_SESSION["user_login"])) //check condition user login not direct back to index.php page
{
 header("location: user/user_home.php");
} 

Row no 19 – If condition, get the name attribute value login form button btn_login using the method $_REQUEST[ ] array. And the isset() function targets this attribute value by clicking the event.

if(isset($_REQUEST['btn_login'])) //login button name is "btn_login" and set this 

Row no 21 to 23 – Using $_REQUEST [ ] variable method get all values txt_email, txt_password and txt_role by name attribute in the login form fields. Get able form fields all values store in created $email, $password & $role variables.

$email  =$_REQUEST["txt_email"]; //textbox name "txt_email"
$password =$_REQUEST["txt_password"]; //textbox name "txt_password"
$role  =$_REQUEST["txt_role"];  //select option name "txt_role" 

Row no 25 to 33 – three if and else if condition, empty() function checks that all variable value is not null.

if(empty($email)){      
 $errorMsg[]="please enter email"; //check email textbox not empty or null
}
else if(empty($password)){
 $errorMsg[]="please enter password"; //check passowrd textbox not empty or null
}
else if(empty($role)){
 $errorMsg[]="please select role"; //check select option not empty or null
}

Row no 34 – else if condition check each variable value returns true.

else if($email AND $password AND $role)

Row no 36 to 44 – Open the try / catch block, apply the select PDO query in the prepare() statement and select all records.

bindParam() function binds the value of the variables :uemail, :upassword and :urole in query place. And, above all, the values of $email, $password, and $role variables persist. execute() function execute the query statement. 

$select_stmt=$db->prepare("SELECT email,password,role FROM masterlogin
       WHERE
       email=:uemail AND password=:upassword AND role=:urole"); //sql select query
$select_stmt->bindParam(":uemail",$email);
$select_stmt->bindParam(":upassword",$password); //bind all parameter
$select_stmt->bindParam(":urole",$role);
$select_stmt->execute(); //execute query 

Row no 46 to 51 – PDOStatement:: fetch method returns row from the result set. PDO:: FETCH_ASSOC parameter informs PDO to return array value indexed by table column email, password and role. The $row is an array.

All values are stored created new variables $dbemail, $dbpassword and $dbrole.

while($row=$select_stmt->fetch(PDO::FETCH_ASSOC)) //fetch record from MySQL database
{
 $dbemail =$row["email"];
 $dbpassword =$row["password"];  //fetchable record store new variable they are "$dbemail","$dbpassword","$dbrole"
 $dbrole  =$row["role"];
} 

Row no 52 – if condition checks the variables $email, $password, and $role do not return null.

if($email!=null AND $password!=null AND $role!=null) //check taken fields not null after countinue 

Row no 54 – if condition test results the number of rows returnable by rowCount() function is greater than zero (>0).

if($select_stmt->rowCount()>0) //check row greater than "0" after continue 

Row no 56 – if condition, the user typeable form field values and table values must be matched using == operator check.

Note: – The == use of the operator for both operand values is equal to or not.

if($email==$dbemail AND $password==$dbpassword AND $role==$dbrole) //check type textbox email,password,role and fetchable record new variables are true after continue 

Row no 58 to 80 – Then the switch statement occurred, above all condition is true. And within the switch case statement, we store the values of the role name by the $dbrole variable since that variable holds the values of the role name that are already discussed above by the $row array.

switch($dbrole)  //role base user login start
{
 case "admin":
  $_SESSION["admin_login"]=$email;   //session name is "admin_login" and store in "$email" variable
  $loginMsg="Admin... Successfully Login..."; //admin login success message
  header("refresh:3;admin/admin_home.php"); //refresh 3 second after redirect to "admin_home.php" page
  break;
        
 case "employee":
  $_SESSION["employee_login"]=$email;    //session name is "employee_login" and store in "$email" variable
  $loginMsg="Employee... Successfully Login...";  //employee login success message
  header("refresh:3;employee/employee_home.php"); //refresh 3 second after redirect to "employee_home.php" page
  break;
        
 case "user":
  $_SESSION["user_login"]=$email;    //session name is "user_login" and store in "$email" variable
  $loginMsg="User... Successfully Login..."; //user login success message
  header("refresh:3;user/user_home.php");  //refresh 3 second after redirect to "user_home.php" page
  break;
        
 default:
 $errorMsg[]="wrong email or password or role";
} 

case "admin":   If the name of the admin role detected that case, assign the admin_login session key in $_SESSION[ ] array.

Apply the admin login message and the header() function will keep this message within 3 seconds, it will be sent in the admin_home.php page created under the admin folder and break it.

case "employee":   If the name of the employee role was found as the case became, assign employee_login session key in $_SESSION[ ] array.

Push login message for employees. The function header() keeps the message within 3 seconds, Send it to the employee_home.php page that was built in the employee folder and break it.

case "user":  When the user name was found as the case occurred, In $_SESSION[ ] array assign the session key name user_login.

Push user login message and keep the message in 3 seconds with header() function, send it to user_home.php page that was built in the user folder and break it.  

default: – The case statement of the switch provides the default state case. Attach error messages like wrong email or password or role inside the default case.

Note – I haven't explained else condition see any else condition detecting unique condition-based error message. And the error message is defined in the array variable $errorMsg[ ].

6. register.php [ PHP Registration Form ]

Create a registration form for new user data to be registered in the database in this file. This form contains three input boxes and one option to select. The three input box that takes username, email, password and the selection option that takes the name of the role.

Following the registration form, which is responsible for adding different roles in the database by choosing a new user.

<form method="post" class="form-horizontal">
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Userame</label>
 <div class="col-sm-6">
 <input type="text" name="txt_username" class="form-control" placeholder="enter username" />
 </div>
 </div>
    
 <div class="form-group">
 <label class="col-sm-3 control-label">Email</label>
 <div class="col-sm-6">
 <input type="text" name="txt_email" class="form-control" placeholder="enter email" />
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Password</label>
 <div class="col-sm-6">
 <input type="password" name="txt_password" class="form-control" placeholder="enter passowrd" />
 </div>
 </div>
     
 <div class="form-group">
 <label class="col-sm-3 control-label">Select Type</label>
 <div class="col-sm-6">
  <select class="form-control" name="txt_role">
   <option value="" selected="selected"> - select role - </option>
   <option value="employee">Employee</option>
   <option value="user">User</option>
  </select>
 </div>
 </div>
    
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 <input type="submit"  name="btn_register" class="btn btn-primary " value="Register">
 </div>
 </div>
    
 <div class="form-group">
 <div class="col-sm-offset-3 col-sm-9 m-t-15">
 You have a account register here? <a href="index.php"><p class="text-info">Login Account</p></a>  
 </div>
 </div>
     
</form>

PHP Registration Form Visually Below This Type :


PHP Registration Form . Multi User Role Based Login in PHP with MySQL PDO

6.1 PHP Code For Registration Form


Below are PHP codes that register new user data to the database. Validation is also provided in these codes and if you have already registered username or user email, the message would indicate the email or username already exists.

Extra these codes validate the right email format and the length of the password must be 6 characters. It will handle the registration process along with suitable validation.

Below codes a few long but not a hard jump to the explanation of the logic codes to easily comprehend the logic.

<?php

require_once "connection.php";

if(isset($_REQUEST['btn_register'])) //check button name "btn_register" and set this
{
 $username = $_REQUEST['txt_username']; //textbox name "txt_username"
 $email  = $_REQUEST['txt_email']; //textbox name "txt_email"
 $password = $_REQUEST['txt_password']; //textbox name "txt_password"
 $role  = $_REQUEST['txt_role']; //select option name "txt_role"
  
 if(empty($username)){
  $errorMsg[]="Please enter username"; //check username textbox not empty or null
 }
 else if(empty($email)){
  $errorMsg[]="Please enter email"; //check email textbox not empty or null
 }
 else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
  $errorMsg[]="Please enter a valid email address"; //check proper email format 
 }
 else if(empty($password)){
  $errorMsg[]="Please enter password"; //check passowrd textbox not empty or null
 }
 else if(strlen($password) < 6){
  $errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters
 }
 else if(empty($role)){
  $errorMsg[]="Please select role"; //check not select role 
 }
 else
 { 
  try
  { 
   $select_stmt=$db->prepare("SELECT username, email FROM masterlogin 
          WHERE username=:uname OR email=:uemail"); // sql select query
   $select_stmt->bindParam(":uname",$username);   
   $select_stmt->bindParam(":uemail",$email);      //bind parameters
   $select_stmt->execute();
   $row=$select_stmt->fetch(PDO::FETCH_ASSOC); //execute query and fetch record store in "$row" variable
   
   if($row["username"]==$username){
    $errorMsg[]="Sorry username already exists"; //check new user type username already exists or not in username textbox
   }
   else if($row["email"]==$email){
    $errorMsg[]="Sorry email already exists"; //check new user type email already exists or not in email textbox
   }
   
   else if(!isset($errorMsg))
   {
    $insert_stmt=$db->prepare("INSERT INTO masterlogin(username,email,password,role) VALUES(:uname,:uemail,:upassword,:urole)"); //sql insert query     
    $insert_stmt->bindParam(":uname",$username); 
    $insert_stmt->bindParam(":uemail",$email);     //bind all parameter 
    $insert_stmt->bindParam(":upassword",$password);
    $insert_stmt->bindParam(":urole",$role);
    
    if($insert_stmt->execute())
    {
     $registerMsg="Register Successfully.....Wait Login page"; //execute query success message
     header("refresh:4;index.php"); //refresh 4 second and redirect to index.php page
    }
   }
  }
  catch(PDOException $e)
  {
   echo $e->getMessage();
  }
 }
}
?>

6.2 Registration Codes Logic Explanation


Row no 3 – Add a connection file to the database using the require_once function. Via the database file object $db, to fire PDO queries.

Row no 5 – If condition, use the method $_REQUEST[ ] array to get the name attribute value registration form button btn_register. And the isset() function targets the value of this attribute by clicking on the event.

if(isset($_REQUEST['btn_register'])) //check button name "btn_register" and set this 

Row no 7 to 10 – Using $_REQUEST[ ] array method gets all txt_username, txt_email, txt_password, and txt_role values by name attribute in the fields of the registration form. Get form fields that store all values in created variables $username, $email, $password & $role.

$username = $_REQUEST['txt_username']; //textbox name "txt_username"
$email  = $_REQUEST['txt_email']; //textbox name "txt_email"
$password = $_REQUEST['txt_password']; //textbox name "txt_password"
$role  = $_REQUEST['txt_role']; //select option name "txt_role" 

Row no 12 to 29 – If and else condition verify form fields all values not null using the function empty(). As well as checking valid email address format and password length at least 6 characters must be needed.

filter_var – Filter a variable with a specified filter ( according to php.net ).

FILTER_VALIDATE_EMAIL –  The FILTER_VALIDATE_EMAIL filter validates an e-mail address ( according to php.net ).

I filter $email variable value here that is taken from user input to check valid email address format.

strlen() – Returns the length of the given string. ( according to php.net ).

Here I check the variable value of $password that takes user inputs less than six (< 6) or not.

if(empty($username)){
 $errorMsg[]="Please enter username"; //check username textbox not empty or null
}
else if(empty($email)){
 $errorMsg[]="Please enter email"; //check email textbox not empty or null
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
 $errorMsg[]="Please enter a valid email address"; //check proper email format 
}
else if(empty($password)){
 $errorMsg[]="Please enter password"; //check passowrd textbox not empty or null
}
else if(strlen($password) < 6){
 $errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters
}
else if(empty($role)){
 $errorMsg[]="Please select role"; //check not select role 
} 

Row no 32 to 39 – Inside the try / catch block discussion. Apply PDO select query under the prepare() statement and a select username and email values from the table.

bindParam() function bind the parameter :uname, :uemail values placed within select query. And both values consistent by $username and $email variables. The function execute() executes a PDO query statement.

PDOStatement:: fetch method extracts a row from the set of results. PDO:: FETCH_ASSOC parameter tells PDO to retrieve array value indexed by username and email of the table column. The array is $row.

$select_stmt=$db->prepare("SELECT username, email FROM masterlogin 
       WHERE username=:uname OR email=:uemail"); // sql select query
$select_stmt->bindParam(":uname",$username);   
$select_stmt->bindParam(":uemail",$email);      //bind parameters
$select_stmt->execute();
$row=$select_stmt->fetch(PDO::FETCH_ASSOC); //execute query and fetch record store in "$row" variable 

Row no 41 to 46 – If and if-else condition checks the new user has entered the username and the email value already exists from the table or not.

if($row["username"]==$username){
 $errorMsg[]="Sorry username already exists"; //check new user type username already exists or not in username textbox
}
else if($row["email"]==$email){
 $errorMsg[]="Sorry email already exists"; //check new user type email already exists or not in email textbox
} 

Row no 48 to 60 – else if condition, the isset() function checks that the $errorMsg variable does not return any error message, and applies the PDO insert query in prepare() statement.

The function bindParam() binds the values :uname, :uemail, :upassword and :urole in the insert query. All parameter values carry variables along with $username, $email, $password, and $role.

Finally, the execute() function executes the insert query statement, displays the register successfully message and the header() function keeps this message at 4 seconds and sends it to index.php page.

else if(!isset($errorMsg))
{
    $insert_stmt=$db->prepare("INSERT INTO masterlogin(username,email,password,role) VALUES(:uname,:uemail,:upassword,:urole)"); //sql insert query     
    $insert_stmt->bindParam(":uname",$username); 
    $insert_stmt->bindParam(":uemail",$email);     //bind all parameter 
    $insert_stmt->bindParam(":upassword",$password);
    $insert_stmt->bindParam(":urole",$role);
    
    if($insert_stmt->execute())
    {
  $registerMsg="Register Successfully.....Wait Login page"; //execute query success message
  header("refresh:4;index.php"); //refresh 4 second and redirect to index.php page
    }
}

7. admin_home.php

Row no 8 – Verify that the admin session key admin_login has not been found then returns the header() function onto the index page. Because the admin role does not have direct access to the admin page. The session key is confirmation from the index/login form that the admin is authenticated. 

Row no 13 – This condition checks whether the employee's role session key employee_login is found then the header() function sends to the employee_home.php page. Because the admin page doesn't allow permissions employee role to access this page.

Row no 18 – Also this condition works above, if the user's role user_login session key is found then the function header() delivers to the user_home.php page. The user role does not access the admin page because permissions were still not allowed on this page.

Row no 23 to 29 – Get admin_login session key to admin role and view e-mail admin value using echo.

<center>
 <h1>Admin Page</h1>
    
 <h3>
 <?php
  session_start();

  if(!isset($_SESSION['admin_login'])) //check unauthorize user not direct access in "admin_home.php" page
  {
   header("location: ../index.php");  
  }

  if(isset($_SESSION['employee_login'])) //check employee login user not access in "admin_home.php" page
  {
   header("location: ../employee/employee_home.php"); 
  }

  if(isset($_SESSION['user_login'])) //check user login user not access in "admin_home.php" page
  {
   header("location: ../user/user_home.php");
  }
  
  if(isset($_SESSION['admin_login']))
  {
  ?>
   Welcome,
  <?php
   echo $_SESSION['admin_login'];
  }
  ?>
 </h3>
  <a href="../logout.php">Logout</a>
</center>

Admin Account Visually Below This Type :


admin account

8. employee_home.php

Row no 9 – Here scan the employee_login session key of the employee role that was not found then sending the header() function on the index page.

Row no 14 – Here we get admin_login session key if you find sending by header function to admin_home.php page. Because the employee account has not allowed admin permissions to access this page.

Row no 19 – The same here we get user_login session key of user role if we consider sending by header() function to user_home.php page. Not to access the employee account or page, either, the user role.

Row no 24to 30 – Take employee_login session key of employee role and use echo to display employee email address value.

<center>
 <h1>Employee Page</h1>
    
 <h3>
 <?php
    
 session_start();

 if(!isset($_SESSION['employee_login'])) //check unauthorize user not direct access in "employee_home.php" page
 {
  header("location: ../index.php");
 }

 if(isset($_SESSION['admin_login'])) //check admin login user not access in "employee_home.php" page
 {
  header("location: ../admin/admin_home.php");
 }

 if(isset($_SESSION['user_login'])) //check user login user not access in "employee_home.php" page
 {
  header("location: ../user/user_home.php");
 }
    
 if(isset($_SESSION['employee_login']))
 {
 ?>
  Welcome,
 <?php
  echo $_SESSION['employee_login'];
 }
 ?>
 </h3>
  <a href="../logout.php">Logout</a>
</center>

Employee Account Visually Below This Type :


employee account

9. user_home.php

Row no 9 – We apply admin and employee page account tactics on this page. We get user_login session key of user role, if not found then the header() function transfers immediately to the index page because any user role does not directly access the user account.

Row no 14 – In this condition we obtain the admin_login session key of the admin role if it is detected then sending by header() function to the admin account.

Row no 19 – Exactly here we use the same techniques of the above condition in this condition. We receive employee_login session key of employee role if find then deliver by header() function to employee account.

Row no 24 to 30 – Finally, accept user_login session key of user role and use echo to display active user login email address.

<center>
 <h1>User Page</h1>
    
 <h3>
 <?php
    
 session_start();

 if(!isset($_SESSION['user_login'])) //check unauthorize user not direct access in "user_home.php" page
 {
  header("location: ../index.php");
 }

 if(isset($_SESSION['admin_login'])) //check admin login user not access in "user_home.php" page
 {
  header("location: ../admin/admin_home.php");
 }

 if(isset($_SESSION['employee_login'])) //check employee login user not access in "employee_home.php" page
 {
  header("location: ../employee/employee_home.php");
 }

 if(isset($_SESSION['user_login']))
 {
 ?>
  Welcome,
 <?php
  echo $_SESSION['user_login'];
 }
 ?>
 </h3>
  <a href="../logout.php">Logout</a>
</center>

User Account Visually Below This Type :


user account



10. logout.php

In this file, along with click logout hyperlink, we destroy the session from the whole role's account and send it all to the index/login page.

<?php
session_start();

header("location:index.php");

session_destroy();

?>

Congrats to completely develop multi user role based login system.

7 comments:

  1. is it ok to send me to source code of this document?

    ReplyDelete
  2. error message not displaying

    ReplyDelete
  3. These Codes Paste before form tag all error messages are displaying perfectly.

    <?php
    if(isset($errorMsg))
    {
    foreach($errorMsg as $error)
    {
    echo $error;
    }
    }
    if(isset($loginMsg))
    {
    echo $loginMsg;
    }

    ReplyDelete
  4. where is source code where is download link

    ReplyDelete
  5. Hi Vivek currently I not put source codes zip file of this tutorial. But see all codes I explain properly. If you face any issue about this tutorial codes then contact me.

    ReplyDelete
  6. hye.. i have problem with the coding.. as i login, it does not function well and it kind like refresh..why is it like that?

    ReplyDelete
  7. Check your login codes all accessories like button name attribute click event, text box name attribute, select query, folder path location etc. This project works properly.

    ReplyDelete