Home  >  Article  >  Backend Development  >  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

PHPz
PHPzOriginal
2023-08-06 15:21:03702browse

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`)
);

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`)
);

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`)
);
  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;
}

// 其他页面逻辑...
?>

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);
}
?>

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>

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:
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