Adding Role-Based Access Control
InRole-based access control allows authenticated users to perform only the previousactions tutorials,permitted by their stored role. This example uses two roles: user and admin.
Database role
A suitable users couldtable register, log in, access protected pages and log out. In this tutorial, you will add roles to your user accounts and restrict access to pages based on those roles.
The system will support three roles:contains:
admin
teacher
student
Add a Role Column to the Users Table
Open phpMyAdmin and select your project_db database.
Run the following SQL statement:
ALTER TABLE users
ADD role VARCHAR(20) NOT NULL DEFAULT 'student';user'
ThisOrdinary createsregistration must always create user accounts. Promote a newfictional fieldtest calledaccount through roleanda automaticallycontrolled assignsadministrator process or directly in the valuelocal development studentto any existing or future users.
Check the Updated Table
Run:
SELECT * FROM users;
You should now see a role column.
Example:
Update Existing Users
Update the admin account:database:
UPDATE users
SET role = 'admin'
WHERE username = 'admin'admin_demo';
UpdateDo thenot teacherallow account:
UPDATEpublic usersform SETto rolesubmit =its 'teacher'own WHERE username = 'teacher';
Run:
SELECT * FROM users;
Example:
Store the Usertrusted Rolerole inat login
After verifying the Session
Open:password:
login.phpsession_regenerate_id(true);
Locate:
$_SESSION["user_id"] = $user["user_id"];
$_SESSION["username"] = $user["username"];
Add:
$_SESSION["role"] = $user["role"];
The completed section should look like:
$_SESSION["user_id"] =(int) $user["user_id"];
$_SESSION["username"] = $user["username"];
$_SESSION["role"] = $user["role"];
header("Location: members.php");
exit();
This stores the user's role when they log in.
Display the User Role
Open:
members.php
Add:
<p>Role:
<?php echo $_SESSION["role"]; ?>
</p>
Example:
<p>Welcome,
<?php echo $_SESSION["username"]; ?>
</p>
<p>Role:
<?php echo $_SESSION["role"]; ?>
</p>
Save the file and log in.
Example result:
Welcome, admin
Role: admin
CreateRequire an Admin Pageadministrator
Create a new file called:
admin.php
Add the following code:
<?php
session_start();
if (!isset($_SESSION["user_id"])) {
header("Location: login.php");
exit();exit;
}
if (($_SESSION["role"] !=?? "admin"") {
die("Access denied.");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin Area</title>
</head>
<body>
<h1>Admin Area</h1>
<p>Welcome,
<?php echo $_SESSION["username"]; ?>
</p>
</body>
</html>
Save the file.
Test Admin Access
Log in as:
admin
Visit:
http://localhost/admin.php
The page should load successfully.
Test Non-Admin Access
Log out.
Log in as:
teacher
or
student
Visit:
http://localhost/admin.php
You should see:
Access denied.
Add an Admin Link
Open:
members.php
Add:
<?php if ($_SESSION["role"] == "admin") {
?>http_response_code(403);
<p>exit("You <ado href=not have permission to access this page."admin.php">Admin Area</a>
</p>
<?php);
} ?>
Example:Authentication asks “Who is signed in?” Authorisation asks “May that user perform this action?” Both checks are required.
<p>Reusable <aadministrator href="logout.php">Logout</a>
</p>
<?php if ($_SESSION["role"] == "admin") { ?>
<p>
<a href="admin.php">Admin Area</a>
</p>
<?php } ?>
guard
NowCreate onlyincludes/require-admin.php administrators will seecontaining the checks above, then require it from every administrative display and processing route.
Test matrix
Complete
SQL
CommandsLogged
ALTERout
Complete Role Storage CodeCheck
$_SESSION["user_id"] = $user["user_id"];
$_SESSION["username"] = $user["username"];
$_SESSION["role"] = $user["role"];
header("Location: members.php");
exit();
You now have a role-based access system that supports:
AdminusersRoles areuserandadmin.TeacherusersRole comes from the stored user record.StudentusersAdministrative processing is protected.
You can use the same technique to create protected pages for different user groups.
Next tutorial: Creating a Navigation Menu Based on User Roles.
