Home Backend Development PHP Tutorial How to use PHP to implement the role permission control function of CMS system

How to use PHP to implement the role permission control function of CMS system

Aug 06, 2023 pm 03:21 PM
php cms Role permission control

How to use PHP to implement the role permission control function of the CMS system

When developing a CMS system, it is often necessary to implement a role permission control function to ensure that different users can only access the pages and functions for which they have permission. . This article will introduce how to use PHP to implement such role permission control function, and attach code examples.

  1. Database design

First, we need to design a database table to store user role and permission information. Three tables can be created: users, roles and permissions.

  • The users table includes basic information of users, such as username, password, etc.
  • The roles table defines the names and descriptions of different roles.
  • The permissions table defines the permissions possessed by each role.

The following is an example design of a database table:

users table:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `role_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);
Copy after login

roles table:

CREATE TABLE `roles` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
);
Copy after login

permissions table:

CREATE TABLE `permissions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role_id` int(11) NOT NULL,
  `page` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
);
Copy after login
  1. Role permission verification

We need to verify the user's permissions before each user accesses a restricted page. The following is a simple implementation example:

<?php
// 获取当前登录用户的角色ID
$role_id = getCurrentUserRole();

// 获取当前页面的路径
$page = $_SERVER['REQUEST_URI'];

// 验证用户权限
if (!checkUserPermission($role_id, $page)) {
    echo "您没有权限访问该页面!";
    exit;
}

// 其他页面逻辑...
?>
Copy after login

As you can see, in the above example, we first obtain the role ID of the currently logged in user and obtain the path of the current page. Then, call the checkUserPermission function to verify the user's permissions. If the user does not have permission to access the page, we can output the corresponding prompt information and end the program.

  1. Implementing the checkUserPermission function

The following is an example of a possible implementation of the checkUserPermission function:

<?php
function checkUserPermission($role_id, $page) {
    // 查询用户的角色对应的权限
    $query = "SELECT COUNT(*) FROM permissions WHERE role_id = :role_id AND page = :page";
    // 执行查询
    // 这里使用的是PDO块,你也可以使用其他数据库操作方式,如mysqli等
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':role_id', $role_id);
    $stmt->bindParam(':page', $page);
    $stmt->execute();

    // 检查是否有权限
    $count = $stmt->fetchColumn();
    return ($count > 0);
}
?>
Copy after login

In the above example, we first wrote a SQL Query statement to query the number of permission records corresponding to roles and pages.

Then, we use PDO prepared statements to execute the query. Note that in actual use, you need to modify the corresponding syntax according to your own database connection method and code framework.

Finally, we check the number of query results. If it is greater than 0, it means that the user has permission to access the page, otherwise there is no permission.

  1. Role permissions management page

Finally, we can create a management page to set the corresponding relationship between roles and permissions. The following is a simple example:

<?php
// 获取所有角色
$query = "SELECT * FROM roles";
$roles = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);

// 获取所有页面
$query = "SELECT DISTINCT(page) FROM permissions";
$pages = $pdo->query($query)->fetchAll(PDO::FETCH_COLUMN);

// 检查表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 清空权限表
    $query = "TRUNCATE TABLE permissions";
    $pdo->exec($query);

    // 重新插入权限记录
    foreach ($roles as $role) {
        $role_id = $role['id'];
        foreach ($pages as $page) {
            if (isset($_POST['permission'][$role_id][$page])) {
                $query = "INSERT INTO permissions (role_id, page) VALUES (:role_id, :page)";
                $stmt = $pdo->prepare($query);
                $stmt->bindParam(':role_id', $role_id);
                $stmt->bindParam(':page', $page);
                $stmt->execute();
            }
        }
    }

    echo "权限设置已保存!";
}
?>

<form method="POST">
    <?php foreach ($roles as $role) : ?>
        <h3><?php echo $role['name']; ?></h3>
        <?php foreach ($pages as $page) : ?>
            <div>
                <input type="checkbox" name="permission[<?php echo $role['id']; ?>][<?php echo $page; ?>]">
                <label><?php echo $page; ?></label>
            </div>
        <?php endforeach; ?>
    <?php endforeach; ?>
    <button type="submit">保存权限设置</button>
</form>
Copy after login

In the above example, we first query all roles and pages and save them to the $roles and $pages arrays respectively.

Then, if the form is submitted, we first clear the permission table and then re-insert the permission record. Here we use multi-dimensional arrays to handle the correspondence between different roles and pages.

Finally, we output a form for selecting roles and page permissions. Users can check the corresponding permissions and click the save button to save the permission settings.

Summary

Through the above code examples and steps, we can implement a role-based permission control function. When a user accesses a restricted page, the system will verify the corresponding relationship between the user's role and the page's permissions, and give corresponding prompts or allow access.

Of course, this is just a simple example. In actual development, it needs to be expanded and optimized according to specific project needs. At the same time, we should also pay attention to security and data integrity issues, such as precompiling database queries and preventing SQL injection.

I hope this article will help you understand how to use PHP to implement the role permission control function of the CMS system. I wish you smooth development!

The above is the detailed content of How to use PHP to implement the role permission control function of CMS system. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

See all articles