Skip to main content

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 rolethrough anda automaticallycontrolled assignsadministrator process or directly in the valuelocal studentdevelopment to any existing or future users.

Check the Updated Table

Run:

SELECT * FROM users;

You should now see a role column.

Example:

user_id username password role 1 admin $2y$10$... student 2 teacher $2y$10$... student

Update Existing Users

Update the admin account:database:

UPDATE users
SET role = 'admin'
WHERE username = 'admin'admin_demo';

UpdateDo thenot teacherallow account:

a
UPDATEpublic usersform SETto rolesubmit =its 'teacher'own WHERE username = 'teacher';

Run:

SELECT * FROM users;

Example:

user_id username role 1 admin admin 2 teacher teacher 3 testuser student

role.

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.

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

Account state User page Admin Areapage link.

Complete SQL CommandsLogged

ALTERout
TABLERedirect usersto ADDlogin Redirect to login Standard user Allowed 403 response Administrator Allowed Allowed Changed form/URL value No role VARCHAR(20)change NOTNo NULLadditional DEFAULTaccess 'student'; UPDATE users SET role = 'admin' WHERE username = 'admin'; UPDATE users SET role = 'teacher' WHERE username = 'teacher'; SELECT * FROM users;

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:

  • Admin usersRoles are user and admin.
  • Teacher usersRole comes from the stored user record.
  • Student usersAdministrative processing is protected.
 Direct URLs are tested.  Denied access uses an appropriate response.

You can use the same technique to create protected pages for different user groups.

Next tutorial: Creating a Navigation Menu Based on User Roles.