Вы находитесь на странице: 1из 8

Creating multi user role based admin using php mysql and

bootstrap
144
BY SHAHRUKH KHAN ON NOVEMBER 20, 2014PHP
Last two weeks I was quite busy with projects and hardly had any spare time left for writing blogs. I
had a huge backlog of mails requesting for tutorials. One thing I found common among them was
creating a multi user role based admin feature. I googled for the article so I can give them links but I
was not able to find useful tutorial. So i decided to make it myself for my readers. In this tutorial I will
be Creating multi user role based admin using php mysql and bootstrap library.

View Demo

What is multi user role based admin?


For novice users let me explain what this article is all about. Suppose you have an online inventory store. You
have multiple employee each has their specific roles. i.e some person are responsible for feeding data (Data
Operator), some are responsible for customer support and some for sales. In this case you dont want all your
modules/data to be available to every one of them. So what you have to do is to assign a role to them, and then
they will have the privilege to access limited data only.

In this tutorial I am not going to make a full fledged admin panel. I will show the trick using mysql database and
php logic to create multi user admin. Follow the steps below.

Step 1. Create a database and add modules,system users, role and their rights.
The first step is to create a database. I have created a database named multi-admin. Create some modules that
you will be using in your application. Check the sample sql below.

2
3 CREATE DATABASE `multi-admin`;
4 USE `multi-admin`;
5
6 CREATE TABLE IF NOT EXISTS `module` (
7 `mod_modulegroupcode` varchar(25) NOT NULL,
8 `mod_modulegroupname` varchar(50) NOT NULL,
9 `mod_modulecode` varchar(25) NOT NULL,
10 `mod_modulename` varchar(50) NOT NULL,
11 `mod_modulegrouporder` int(3) NOT NULL,
12 `mod_moduleorder` int(3) NOT NULL,
13 `mod_modulepagename` varchar(255) NOT NULL,
14 PRIMARY KEY (`mod_modulegroupcode`,`mod_modulecode`),
15 UNIQUE(`mod_modulecode`)
16 ) ENGINE=INNODB DEFAULT CHARSET=utf8;
Once you have created modules table, feed some data into it. I have used purchases, sales, stocks and Shipping,
payment and taxes. So there are 6 modules in two groups.

2
3 INSERT INTO module (mod_modulegroupcode, mod_modulegroupname, mod_modulecode, mod_modulename, mod_
4 modulegrouporder, mod_moduleorder, mod_modulepagename) VALUES
5 ("INVT","Inventory", "PURCHASES","Purchases", 2, 1,'purchases.php'),
6 ("INVT","Inventory", "STOCKS","Stocks", 2, 2,'stocks.php'),
7 ("INVT","Inventory", "SALES","Sales", 2, 3,'sales.php'),
8 ("CHECKOUT","Checkout","SHIPPING","Shipping", 3, 1,'shipping.php'),
9 ("CHECKOUT","Checkout","PAYMENT","Payment", 3, 2,'payment.php'),
("CHECKOUT","Checkout","TAX","Tax", 3, 3,'tax.php');
Create roles that will be assigned to the admins.

2
3 CREATE TABLE IF NOT EXISTS `role` (
4 `role_rolecode` varchar(50) NOT NULL,
5 `role_rolename` varchar(50) NOT NULL,
6 PRIMARY KEY (`role_rolecode`)
7 ) ENGINE=INNODB DEFAULT CHARSET=utf8;
8
9 INSERT INTO `role` (`role_rolecode`, `role_rolename`) VALUES
10 ('SUPERADMIN', 'Super Admin'),
11 ('ADMIN', 'Administrator');
Add system user/admin who will manage the application. Assign each admin with a role.

2
CREATE TABLE IF NOT EXISTS `system_users` (
3
`u_userid` int(11) AUTO_INCREMENT NOT NULL,
4
`u_username` varchar(100) NOT NULL,
5
`u_password` varchar(255) NOT NULL,
6
`u_rolecode` varchar(50) NOT NULL,
7
PRIMARY KEY (`u_userid`),
8
FOREIGN KEY (`u_rolecode`) REFERENCES `role` (`role_rolecode`) ON UPDATE CASCADE ON DELETE RES
9
TRICT
10
) ENGINE=INNODB DEFAULT CHARSET=utf8;
11
12
INSERT INTO `system_users` (`u_username`, `u_password`, `u_rolecode`) VALUES
13
('shahrukh', '123456', 'SUPERADMIN'),
14
('ronaldo', 'ronaldo', 'ADMIN');
The final step is to give each role the privilege to access modules. I have used 4 options i.e create, edit, view
and delete.

2
3 INSERT INTO `role_rights` (`rr_rolecode`, `rr_modulecode`, `rr_create`, `rr_edit`, `rr_delete`, `rr_view`) VALUES
4 ('SUPERADMIN', 'PURCHASES', 'yes', 'yes', 'yes', 'yes'),
5 ('SUPERADMIN', 'STOCKS', 'yes', 'yes', 'yes', 'yes'),
6 ('SUPERADMIN', 'SALES', 'yes', 'yes', 'yes', 'yes'),
7 ('SUPERADMIN', 'SHIPPING', 'yes', 'yes', 'yes', 'yes'),
8 ('SUPERADMIN', 'PAYMENT', 'yes', 'yes', 'yes', 'yes'),
9 ('SUPERADMIN', 'TAX', 'yes', 'yes', 'yes', 'yes'),
10
11 ('ADMIN', 'PURCHASES', 'yes', 'yes', 'yes', 'yes'),
12 ('ADMIN', 'STOCKS', 'no', 'no', 'no', 'yes'),
13 ('ADMIN', 'SALES', 'no', 'no', 'no', 'no'),
14 ('ADMIN', 'SHIPPING', 'yes', 'yes', 'yes', 'yes'),
15 ('ADMIN', 'PAYMENT', 'no', 'no', 'no', 'yes'),
16 ('ADMIN', 'TAX', 'no', 'no', 'no', 'no');

Step 2. Create files for every single modules.


This step is very easy. You have to create files for each modules based on names you have given in the database
(module table). Apart from the 6 pages that are given the database, you have to create 3 more pages
viz. login.php(user will login), dashboard.php (user will see the menu/modules), and logout.php (to clear the
session).

Step 3. Creating login form.


If you have followed my earlier tutorials, you should know that I use PDO classes to access the database. If you
are new to PDO classes try learning it from a sample mini-project Simple address book with php and mysql
using pdo.

<form class="form-horizontal" name="contact_form" id="contact_form" method="post" action="">


2
<input type="hidden" name="mode" value="login" >
3
4
<fieldset>
5
<div class="form-group">
6
<label class="col-lg-2 control-label" for="username"><span class="required">*</span>Username:</label>
7
<div class="col-lg-6">
8
<input type="text" value="" placeholder="User Name" id="username" class="form-control" name="user
9
name" required="" >
10
</div>
11
</div>
12
13
<div class="form-group">
14
<label class="col-lg-2 control-label" for="user_password"><span class="required">*</span>Password:</la
15
bel>
16
<div class="col-lg-6">
17
<input type="password" value="" placeholder="Password" id="user_password" class="form-control" na
18
me="user_password" required="" >
19
</div>
20
</div>
21
22
<div class="form-group">
23
<div class="col-lg-6 col-lg-offset-2">
24
<button class="btn btn-primary" type="submit">Submit</button>
25
</div>
26
</div>
27
</fieldset>
</form>
Create a file name config.php to set up basic configuration.
2
error_reporting( E_ALL &amp; ~E_DEPRECATED &amp; ~E_NOTICE );
3
ob_start();
4
session_start();
5
6
define('DB_DRIVER', 'mysql');
7
define('DB_SERVER', 'localhost');
8
define('DB_SERVER_USERNAME', 'root');
9
define('DB_SERVER_PASSWORD', '');
10
define('DB_DATABASE', 'multi-admin');
11
12
define('PROJECT_NAME', 'Create Multi admin using php mysql and bootstrap library');
13
$dboptions = array(
14
PDO::ATTR_PERSISTENT =&gt; FALSE,
15
PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC,
16
PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION,
17
PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8',
18
);
19
20
try {
21
$DB = new PDO(DB_DRIVER.':host='.DB_SERVER.';dbname='.DB_DATABASE, DB_SERVER_USERNAME, D
22
B_SERVER_PASSWORD , $dboptions);
23
} catch (Exception $ex) {
24
echo $ex-&gt;getMessage();
25
die;
26
}
27
28
require_once 'functions.php';
29
30
//get error/success messages
31
if ($_SESSION["errorType"] != "" &amp;&amp; $_SESSION["errorMsg"] != "" ) {
32
$ERROR_TYPE = $_SESSION["errorType"];
33
$ERROR_MSG = $_SESSION["errorMsg"];
34
$_SESSION["errorType"] = "";
35
$_SESSION["errorMsg"] = "";
36
}
Validating user login using PHP

2
3 $mode = $_REQUEST["mode"];
4 if ($mode == "login") {
5 $username = trim($_POST['username']);
6 $pass = trim($_POST['user_password']);
7
8 if ($username == "" || $pass == "") {
9
10 $_SESSION["errorType"] = "danger";
11 $_SESSION["errorMsg"] = "Enter manadatory fields";
12 } else {
13 $sql = "SELECT * FROM system_users WHERE u_username = :uname AND u_password = :upass ";
14
15 try {
16 $stmt = $DB->prepare($sql);
17
18 // bind the values
19 $stmt->bindValue(":uname", $username);
20 $stmt->bindValue(":upass", $pass);
21
22 // execute Query
23 $stmt->execute();
24 $results = $stmt->fetchAll();
25
26 if (count($results) > 0) {
27 $_SESSION["errorType"] = "success";
28 $_SESSION["errorMsg"] = "You have successfully logged in.";
29
30 $_SESSION["user_id"] = $results[0]["u_userid"];
31 $_SESSION["rolecode"] = $results[0]["u_rolecode"];
32 $_SESSION["username"] = $results[0]["u_username"];
33
34 redirect("dashboard.php");
35 exit;
36 } else {
37 $_SESSION["errorType"] = "info";
38 $_SESSION["errorMsg"] = "username or password does not exist.";
39 }
40 } catch (Exception $ex) {
41
42 $_SESSION["errorType"] = "danger";
43 $_SESSION["errorMsg"] = $ex->getMessage();
44 }
45 }
46 // redirect function is found in functions.php page
47 redirect("index.php");
48 }
Once you are logged in you are redirected to dashboard.php where you will see the menu/modules that are
assigned as per your role. Your role is saved in session when you are logged in.

2
3 // if the rights are not set then add them in the current session
4 if (!isset($_SESSION["access"])) {
5
6 try {
7
8 $sql = "SELECT mod_modulegroupcode, mod_modulegroupname FROM module "
9 . " WHERE 1 GROUP BY `mod_modulegroupcode` "
10 . " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
11
12 $stmt = $DB->prepare($sql);
13 $stmt->execute();
14 // modules group
15 $commonModules = $stmt->fetchAll();
16
17 $sql = "SELECT mod_modulegroupcode, mod_modulegroupname, mod_modulepagename, mod_modulecode, m
18 od_modulename FROM module "
19 . " WHERE 1 "
20 . " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
21
22 $stmt = $DB->prepare($sql);
23 $stmt->execute();
24 // all modules
25 $allModules = $stmt->fetchAll();
26
27 $sql = "SELECT rr_modulecode, rr_create, rr_edit, rr_delete, rr_view FROM role_rights "
28 . " WHERE rr_rolecode = :rc "
29 . " ORDER BY `rr_modulecode` ASC ";
30
31 $stmt = $DB->prepare($sql);
32 $stmt->bindValue(":rc", $_SESSION["rolecode"]);
33
34 $stmt->execute();
35 // modules based on user role
36 $userRights = $stmt->fetchAll();
37
38 $_SESSION["access"] = set_rights($allModules, $userRights, $commonModules);
39
40 } catch (Exception $ex) {
41
42 echo $ex->getMessage();
43 }
}
In the above script all the data are passed into a function named set_rights() which return an array based on user
roles.

2
function set_rights($menus, $menuRights, $topmenu) {
3
$data = array();
4
5
for ($i = 0, $c = count($menus); $i < $c; $i++) {
6
7
$row = array();
8
for ($j = 0, $c2 = count($menuRights); $j < $c2; $j++) {
9
if ($menuRights[$j]["rr_modulecode"] == $menus[$i]["mod_modulecode"]) {
10
if (authorize($menuRights[$j]["rr_create"]) || authorize($menuRights[$j]["rr_edit"]) ||
11
authorize($menuRights[$j]["rr_delete"]) || authorize($menuRights[$j]["rr_view"])
12
){
13
14
$row["menu"] = $menus[$i]["mod_modulegroupcode"];
15
$row["menu_name"] = $menus[$i]["mod_modulename"];
16
$row["page_name"] = $menus[$i]["mod_modulepagename"];
17
$row["create"] = $menuRights[$j]["rr_create"];
18
$row["edit"] = $menuRights[$j]["rr_edit"];
19
$row["delete"] = $menuRights[$j]["rr_delete"];
20
$row["view"] = $menuRights[$j]["rr_view"];
21
22
$data[$menus[$i]["mod_modulegroupcode"]][$menuRights[$j]["rr_modulecode"]] = $row;
23
$data[$menus[$i]["mod_modulegroupcode"]]["top_menu_name"] = $menus[$i]["mod_modulegroupname"
24
];
25
}
26
}
27
}
28
}
29
30
return $data;
31
}
32
33
// this function is used by set_rights() function
34
function authorize($module) {
35
return $module == "yes" ? TRUE : FALSE;
36
}
Once you have all the modules based on your role in a session variable. Display it as list menu.
2
3 <ul>
4 <?php foreach ($_SESSION["access"] as $key => $access) { ?>
5 <li>
6 <?php echo $access["top_menu_name"]; ?>
7 <?php
8 echo '<ul>';
9 foreach ($access as $k => $val) {
10 if ($k != "top_menu_name") {
11 echo '<li><a href="' . ($val["page_name"]) . '">' . $val["menu_name"] . '</a></li>';
12 ?>
13 <?php
14 }
15 }
16 echo '</ul>';
17 ?>
18 </li>
19 <?php
20 }
21 ?>
22 </ul>

Step 4. Conditional checking for each modules functionality.


In this step you have to manually check write a security check for a module functionaliy. Let say user has the
right to create, edit and view purchases but not delete it. In this case you have to add a conditional checking
before each buttons/links. See a sample below for purchases.php page module.

2
3 <!-- for creating purchase function -->
4 <?php if (authorize($_SESSION["access"]["INVT"]["PURCHASES"]["create"])) { ?>
5 <button class="btn btn-sm btn-primary" type="button"><i class="fa fa-plus"></i> ADD PURCHASE</button>
6 <?php } ?>
7
8 <!-- for updating purchase function -->
9 <?php if (authorize($_SESSION["access"]["INVT"]["PURCHASES"]["edit"])) { ?>
10 <button class="btn btn-sm btn-info" type="button"><i class="fa fa-edit"></i> EDIT</button>
11 <?php } ?>
12
13 <!-- for view purchase function -->
14 <?php if (authorize($_SESSION["access"]["INVT"]["PURCHASES"]["view"])) { ?>
15 <button class="btn btn-sm btn-warning" type="button"><i class="fa fa-search-plus"></i> VIEW</button>
16 <?php } ?>
17
18 <!-- for delete purchase function -->
19 <?php if (authorize($_SESSION["access"]["INVT"]["PURCHASES"]["delete"])) { ?>
20 <button class="btn btn-sm btn-danger" type="button"><i class="fa fa-trash-o"></i> DELETE</button>
21 <?php } ?>

Step 5. Validation for logged in and non-logged in user.


Another security checking, you can add this checking for individual page. check the two test cases below.
If user is logged in and trying to access login page. User will be redirected to dashboard.
If user is not logged in and trying to access any page expect login page. User will be redirected to login
page.

2
3 // paste this in login page
4 if (isset($_SESSION["user_id"]) && $_SESSION["user_id"] != "") {
5 // if logged in send to dashboard page
6 redirect("dashboard.php");
7 }
8
9 // paste this in any page which require admin authorization
10 if (!isset($_SESSION["user_id"]) || $_SESSION["user_id"] == "") {
11 // not logged in send to login page
12 redirect("index.php");
13 }
You can also add another layer of security check for each modules pages if you want. In case if user is trying to
access a modules using direct page URL but is not assigned for, they must not passed this security check.

2
3 $status = FALSE;
4 if ( authorize($_SESSION["access"]["INVT"]["PURCHASES"]["create"]) ||
5 authorize($_SESSION["access"]["INVT"]["PURCHASES"]["edit"]) ||
6 authorize($_SESSION["access"]["INVT"]["PURCHASES"]["view"]) ||
7 authorize($_SESSION["access"]["INVT"]["PURCHASES"]["delete"]) ) {
8 $status = TRUE;
9 }
10
11 if ($status === FALSE) {
12 die("You dont have the permission to access this page");
13 }

Step 6. Logout Page.


The step is just for clearing the session and redirecting user back to login page.

2
3 session_start();
4 $_SESSION = array();
5 unset($_SESSION);
6 session_destroy();
7 header("location:index.php");
8 exit;
View Demo

Вам также может понравиться