Code for PHP multi user secure login system on single login page

As a web developer, we often face a situation to develop single login page for multiple users based on role using PHP. And also for each user we have to redirect them to different pages. Sounds weird right? Ok, let’s start to create multi-user secure login system using PHP in an easy way. I am assuming that you already set the server to run PHP code and installed MySQL for a database. If you want to setup a server, go through this tutorial - Setup xampp server on Ubuntu. I will try to make this post as more resourceful so that you gain insights on multi-user login system in PHP.

PHP multi user login system

Download Codes

Here we have 6 files for login page, to check credentials, one user file, one admin file, one for database connection and last one is for logout.




Database design

Create database with name login. Here is the database table structure.
login_details table

CREATE TABLE login_details(
  id VARCHAR(15) NOT NULL,
  password VARCHAR(32) NOT NULL,
  salt VARCHAR(32) NOT NULL,
  access_level INT(10) NOT NULL,
  PRIMARY KEY(id)
 )
Here We are creating "login_details" table with 3 attributes ('id', 'password' and 'access_level'). 'id' and 'password' attributes are common. But 'access_level' attribute plays important role here. This attribute used to distinguish between users authorities. You can say it as privilege level. It is very important in user session management. In this tutorial I set access level '0' for normal users and '1' for admin. And salt attribute is to randomize the password hashes for same passwords. First create database and table as mentioned above or else run below php file that automates above process. Run this only on first time.
Code for creating database and 'login_details' table. Replace the values of $host,$username,$pasword with your database credentials.

<?php
$db_name="login"; // Database name
$host="localhost";
$username="root";
$password="hari";
$query="CREATE TABLE login_details(
  id VARCHAR(15) NOT NULL,
  password VARCHAR(32) NOT NULL,
  access_level INT(10) NOT NULL,
  PRIMARY KEY(id)
 )";
try{
 $db = new PDO("mysql:host=$host", $username, $password);
 $db->exec("CREATE DATABASE $db_name");
 $db->query("USE $db_name");
 $db->query($query);
}
catch(PDOException $e){
 die("Database error: ".$e->getMessage());
}
?>

Now let's start coding part.
Code for index.php

<html>
<head>
<title>Codefreax</title>
<style>
.textfield{
 opacity:0.7;
}
.container{
 margin:0px auto;
 width:450px;
 height:250px;
 text-align:center;
 background-color:#F7F7F7;
 border:1px solid #BFBFBF;
 box-shadow:0px 0px 3px #BFBFBF;
}

</style>
</head>
<body>
<h1 style="text-align:center;">Codefreax Multi user login form</h1>
<div class="container"> 
<form action="check.php" method="post">
<h2>Login</h2>
<table style="margin:0px auto">
<tr>
<td>Username: </td><td width="50px"><input class="textfield" type="text" name="uname"/></td>
</tr>
<tr>
<td>Password: </td><td width="50px"><input class="textfield" type="password" name="pwd"/></td>
</tr>
<tr><td></td><td width="50px"><span style="color:#E21111;font-size:12px;">
<?php // To display Error messages
if(isset($_GET['err'])){
if ($_GET['err']==1){
echo "Invalid Credentials.Try username:codefreax, password:password";}
else if($_GET['err']==5){
echo "Successfully Logged out..";}
else if ($_GET['err']==2){
echo "Your trying to access unauthorized page.Please login first";
}
}
?>
</span></td></tr>
</table>
<input type="submit" value="submit"/>
</form>
</div>
</body>
</html>
Above code is a simple form that sends username,password to "check.php". PHP code from line 33 to 43 is to display error messages.

 Code for check.php

<?php
require_once("db.php");
function check_input($r){
 $r=trim($r);
 $r=strip_tags($r);
 $r=stripslashes($r);
 $r=htmlentities($r);
 $r=mysql_real_escape_string($r);
 return $r;
 }
function get_salt($uid){
 $db=get_db();
 $stmt=$db->prepare("SELECT salt FROM login_details WHERE id=?");
 $stmt->execute(array($uid));
 $r=$stmt->fetch(PDO::FETCH_ASSOC);
 return $r['salt'];
}
if (isset($_POST['uname'],$_POST['pwd'])){
 
 $u=check_input($_POST['uname']);
 $p=check_input($_POST['pwd']);
 $saltedpassword=md5(get_salt($u).$p);
 try{
 $db=get_db();
 $stmt=$db->prepare("SELECT * FROM login_details WHERE id=? && password=?");
 $stmt->execute(array($u,$saltedpassword));
 $r=$stmt->fetch(PDO::FETCH_ASSOC);
 if($r){
  session_start();
  $access_level=$r['access_level'];
  $_SESSION['id']=$r['id'];
  $_SESSION['access_level']=$access_level;
  if ($access_level==0){
   header("Location:user.php");
   }
  else if($access_level==1){
   header("Location:admin.php");
   }
  }
 else{
  header("Location:index.php?err=1");
  }
 }
 catch(PDOException $e){
  die("Database error: ".$e->getMessage());
 }
}
else{
 header("Location:index.php");
 }
?>
In the above code I defined my own function check_input()(from line no 2 to 10) to avoid sql injection technique. isset() function is inbuilt function in php that checks if variable is set or not. get_salt() function is to get salt for userID/Username. If username, password matches then it sets a session variables id and access_level. So that remaining pages will came to know if user has authorization or not by simply checking these variables. Then it redirects to different pages according to access levels.




Code for db.php for database connection.

<?php
function get_db(){
 $db_name="login"; // Database name
 $host="localhost";
 $username="root";
 $password="hari";
 $db = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $username, $password);
 return $db;
}
?>

It is good practice to create db.php file because we need to connect database every time on database operations. So by simply including this file we can connect to database.

Code for user.php

<?php
session_start();
if(isset($_SESSION["access_level"]) && $_SESSION["access_level"]==0){
 echo "Hello ".$_SESSION["id"].", This is User page<br/><a href='logout.php'>Logout</a>";
 }
else{
 header("Location:index.php?err=2");
 }
?>

Code for admin.php

<?php
session_start();
if(isset($_SESSION["access_level"]) && $_SESSION["access_level"]==1){
 echo "Hello ".$_SESSION["id"]." This is admin page.<br/><a href='logout.php'>Logout</a>";
 }
else{
 header("Location:index.php?err=2");
 }
?>

Code for logout.php

<?php
session_destroy();
header("Location:index.php?err=5");
?>

That's all friends. This method is very useful for beginners. If you want to share any improvements or bugs comment below. Feel free to ask doubts regarding this tutorial.
Share on Google Plus

About Hari krishna

ThoughtWorker, Computer Science graduate from India. I am passionate programmer, blogger, thinker. I love open-source and linux. I love making friends. Just send me 'hi' to any of my social profiles. I love helping people.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment

We love your Feedback