Table of Contents
主页面
Home Backend Development PHP Tutorial Detailed explanation of PHP's RBAC permissions

Detailed explanation of PHP's RBAC permissions

Mar 22, 2018 am 10:16 AM
php rbac Permissions

This article mainly shares with you a detailed explanation of PHP's RBAC permissions. I hope it can help everyone. First of all, we should know what functions are required for permission management:

 (1). Users can only access specified controls. Controller, specified method

 (2) Users can exist in multiple user groups

 (3) User groups can be selected, specified controller, specified method

(4) You can add controllers and methods

RBAC (Role-Based Access Control, role-based access control), which means users are associated with permissions through roles. Simply put, a user has several roles, and each role has several permissions. In this way, a "user-role-permission" authorization model is constructed. In this model, there is generally a many-to-many relationship between users and roles, and between roles and permissions.

1. Database design

Write five tables, first: user table, role table, function table:

The table of the connection table...Then there is the role function table and the user role table:

2. Administrator's management Page,

(1). Display the user name and role name respectively

(2). According to the change of the drop-down user name, change the role in the corresponding check box

(3). When modifying a user role, first delete the user's corresponding role table and all information about this user, and then add the obtained user name and role code.

Use drop-down list: embed php query and traverse it, display it as a drop-down list

Detailed explanation of PHPs RBAC permissions

<select></select>
Copy after login

Detailed explanation of PHPs RBAC permissions

  <?php     include ("../db.class.php");    $db = new db();    $sql = "select * from qxyh";    $arr = $db->Query($sql);    foreach ($arr as $v)
    {        echo "<option>{$v[2]}</option>";
    }    ?>
Copy after login

Detailed explanation of PHPs RBAC permissions

Copy after login

Detailed explanation of PHPs RBAC permissions

Select the character and use the multi-select box:

Detailed explanation of PHPs RBAC permissions

<p>请选择角色<?php $sjs = "select * from qxzw";$ajs = $db->Query($sjs);foreach ($ajs as $v)
{    echo "<input>{$v[1]} ";
}?>
</p>
<input>
Copy after login

Detailed explanation of PHPs RBAC permissions

Picture:

When the user changes, the corresponding role also changes accordingly, and the role of the person is changed. Information, add and save, the basic idea of ​​adding and saving is to first delete all the role information corresponding to the person in the database, and then fetch the selected part and add it to the database.

First let him select the default role:

<script>  //选中默认角色
    function xuan()
    {        var uid = $("#user").val();
        $.ajax({
            url:"chuli.php",
            data:{uid:uid,type:0},
            type:"POST",
            dataType:"TEXT",
            success:function(data)
            {                var juese = data.trim().split("|");                //拆分完全都变成代号
                var ck = $(".ck");
                ck.prop("checked",false);                for(var i=0;i<ck.length;i++)
                {                    //便利所有的列表
                    if(juese.indexOf(ck.eq(i).val())>=0)
                    {
                        ck.eq(i).prop("checked",true);
                    }
                }
            }
        });
    }</script>
Copy after login

To write his processing page:

<?phpinclude ("../db.class.php");$db = new db();$type = $_POST["type"];switch ($type)
{    case 0:        $uid = $_POST["uid"];        $sql = "select jid from qxyhzw WHERE uid=&#39;{$uid}&#39;";        echo $db->strQuery($sql);break;
}
Copy after login

Let’s take a look at the final result. If the login is successful, you will enter the homepage. If the login fails, An error will be prompted

Come again, save button:

<script>//当用户变化的时候去选中相应角色
        $("#user").change(function(){
            xuan();
        })        //点击确定保存角色信息
        $("#btn").click(function(){            var uid = $("#user").val();            //找到用户名
            var juese = "";//           找到角色代号
            var ck = $(".ck");            //找到所有的checked
            for(var i=0;i<ck.length;i++)
            {//                遍历他
                if(ck.eq(i).prop("checked"))
                {//                    如果他选中了,两个参数是改他的状态
                    //娶过来值;加个|分割一下
                    juese += ck.eq(i).val()+"|";
                }
            }
            juese = juese.substr(0,juese.length-1);//            去掉最后的|            $.ajax({
                url:"chuli.php",
                data:{uid:uid,juese:juese,type:1},
                type:"POST",
                dataType:"TEXT",
                success:function(data){
                    alert("修改成功");
                }
            });

        })
    });</script>
Copy after login

Processing page:

<?phpinclude ("../db.class.php");$db = new db();$type = $_POST["type"];switch ($type)
{ 
   case 1:        $uid = $_POST["uid"];        $juese = $_POST["juese"];        //        首先全部删掉里面的职位
        $sdel = "delete from qxyhzw WHERE uid = &#39;{$uid}&#39;";        $db->Query($sdel,0);        //拆分取到的字符串
        $arr= explode("|",$juese);        foreach ($arr as $v)
        {            $sql = "insert into qxyhzw VALUES (&#39;&#39;,&#39;{$uid}&#39;,&#39;{$v}&#39;)";            $db->query($sql,0);
        }        echo "ok";        break;
}
Copy after login

See the effect:

The role is selected by default;

Select to save after changing:

Management page summary Code:

View Code

Total code for processing page:

<?phpinclude ("../db.class.php");$db = new db();$type = $_POST["type"];switch ($type)
{    case 0:        $uid = $_POST["zhang"];        $sql = "select jid from qxyhzw WHERE uid=&#39;{$uid}&#39;";        echo $db->strQuery($sql);break;    case 1:        $uid = $_POST["zhang"];        $juese = $_POST["juese"];        //        首先全部删掉里面的职位
        $sdel = "delete from qxyhzw WHERE uid = &#39;{$uid}&#39;";        $db->Query($sdel,0);        //拆分取到的字符串
        $arr= explode("|",$juese);        foreach ($arr as $v)
        {            $sql = "insert into qxyhzw VALUES (&#39;&#39;,&#39;{$uid}&#39;,&#39;{$v}&#39;)";            $db->query($sql,0);
        }        echo "ok";        break;
}
Copy after login

3. Login page:

The display is very simple:

<form action="drcl.php" method="post">
    <p>帐号:<input type="text" name="zhang"/></p>
    <p>密码:<input type="text" name="mi"/></p>
    <input type="submit" value="登入"/></form>
Copy after login

Write login processing

<?phpsession_start();include ("../db.class.php");$db = new db();$zhang = $_POST["zhang"];$mi = $_POST["mi"];$sql = "select mi from qxyh WHERE zhang = &#39;{$zhang}&#39;";$mm = $db->strQuery($sql)>0;if($mm = $mi && !empty($mi))
{    $_SESSION["zhang"] = $zhang;    header("location:chaxun.php");
}//else
//{
//    echo "登入失败";
//}
Copy after login

Jump to the main page, main page code:

Everyone’s main page is different

<body><h1 id="主页面">主页面</h1>
Copy after login
<?phpsession_start();include ("../db.class.php");$db = new db();$zhang = "";if(empty($_SESSION["zhang"]))
{    header("location:qx_dr.php");    exit;
}//登入者用户名
    $zhang = $_SESSION["zhang"];//根据用户名查角色$sql = "select jid from qxyhzw WHERE uid = &#39;{$zhang}&#39;";$aql = $db->Query($sql);//根据角色代号查功能代号$attr = array();//定义一个存放功能代号的数组foreach ($aql as $v)
{   $jsid = $v[0];// 角色代号
    $ssql = "select rid from qxgnzw WHERE jid=&#39;{$jsid}&#39;";    $aaql = $db->strQuery($ssql);//拆分
    $adai = explode("|",$aaql);    foreach ($adai as $h)
    {       array_push($attr,$h);
    }
}$attr = array_unique($attr);//去重
//显示foreach ($attr as $k)
{    $ql = "select * from qxgn WHERE code = &#39;{$k}&#39;";    $arr = $db->Query($ql);    $arr[0][0];    $arr[0][1];    echo "<p code=&#39;{$arr[0][0]}&#39;>{$arr[0][1]}</p>";
}?>
Copy after login
</body>
Copy after login

The user experience of using php is not good, it is best to use ajax.

Related recommendations:

php Personnel Access Management (RBAC)

The above is the detailed content of Detailed explanation of PHP's RBAC permissions. 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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles