search
HomeBackend DevelopmentPHP Tutorialphp personnel authority management (RBAC)

Before talking about permission management, you should first know what functions permission management has:

 (1) Users can only access, specify Controller, specified method

 (2) Users can exist in multiple user groups

 (3) User groups You can choose the specified controller and the specified method

(4), you can add the controller and method

RBAC (Role-Based Access Control (role-based access control) is where 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:

Connection Table of tables.. Next is the role function table and user role table:

2. Administrator's Management page,

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

    ?>

(1). Display user name and role name respectively

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

(3). When modifying the user role, first delete the user's corresponding role table and all the information of this user, and then retrieve The username and role code are newly added.

Use the drop-down list: embed the php query and traverse it, display it in the form of a drop-down list

Select the role, use multiple Marquee:


<p style="margin-bottom: 7px;"><p>请选择角色<br/><?php<br/>$sjs = "select * from qxzw";<br/>$ajs = $db->Query($sjs);<br/>foreach ($ajs as $v){    <br/>    echo "<input type=&#39;checkbox&#39; value=&#39;{$v[0]}&#39; class=&#39;ck&#39;/>{$v[1]} ";<br/>}?><br/></p><br/><input type="button" value="确定" id="btn"/><br/></p>

Picture:

##When the user changes, the corresponding role also changes accordingly, and the person's role information is changed and added and saved. The basic idea of ​​adding and saving is to first delete all the role information corresponding to the person in the database, and then retrieve it. The selected part is added to the database.

Let him select the default role first:

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

To write his processing page:

<?php
include ("../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;
}

Let’s take a look at the final result. If you log in successfully, you will enter the homepage. If you log in failed, you will get an error

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

Processing page:

<?php
include ("../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;
}

See the effect:

The role is selected by default;

Choose to save after making changes:

#Management page summary Code:




    无标题文档
    


用户与角色管理

请选择用户
请选择角色 Query($sjs); foreach ($ajs as $v) { echo "{$v[1]} "; } ?>

Total code for processing page:

<?php
include ("../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;
}

##3. Login page:

The display is very simple:


    

帐号:

    

密码:

    

Write login processing

<?php
session_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 "登入失败";
//}
Jump to the main page, main page code:

Everyone’s main page is different of

<h1 id="主页面">主页面</h1>
<?php
session_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>";
}?>

 

 

用php的用户体验不好,最好还是得用ajax

The above is the detailed content of php personnel authority management (RBAC). 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment