


A brief discussion on the seventh bullet of PHP - role-based access control RBAC_PHP tutorial
The above http://www.BkJia.com/kf/201205/129972.html explains to you how to use a loop to output the multiplication table. The logic is relatively simple, but the important thing is to provide you with a program to read it. , methods and ideas for parsing the code, if you have any comments or suggestions, you can comment and criticize....
Okay, no more talk, this article will introduce to you "role-based access control",
When it comes to permissions, everyone has a headache. How can we flexibly control a user’s permissions?
Some students will add fields to the user table or corresponding permission fields to the role table,
There will be a problem with this. It feels very lame and inflexible to implement permissions. Every time a permission is added, a field will be added to the database, which is not conducive to the iterative development of the project
Then we need a very flexible design pattern RBAC, that is, role-based access control;
Let me tell you about this design idea:
First of all, our requirement is to determine whether a user has permission to access the currently operated controller or controller method,
If multiple users have the same permissions at the same time, then we need to assign the same user role to these users, and then only need to control access to operations through the role,
Then our table structure needs to be designed like this. This is very important, as follows:
First data table (user table):
字段名称 | 字段说明 |
id | 用户ID(主键自增) |
username | 用户名 |
password | 用户密码 |
Second data sheet (character sheet):
字段名称 | 字段说明 |
id | 用户角色ID(主键自增) |
name | 用户角色名称 |
The third data table (node table):
字段名称 | 字段说明 |
id | 操作节点ID(主键自增) |
name | 操作节点的名称 |
zh_name | 节点的中文说明 |
We use the third normal form to design the association table. The advantage of this is to avoid data redundancy, and one-to-many and many-to-one relationships can be clearly recorded and organized
The fourth data table (node corresponding role table):
字段名称 | 字段说明 |
role_id | 用户角色ID(外键,关联角色表中的主键ID) |
note_id | 操作节点ID(外键,关联节点表中的主键ID) |
The fifth data table (user corresponding role table):
字段名称 | 字段说明 |
role_id | 用户角色ID(外键,关联角色表中的主键ID) |
user_id | 用户ID(外键,关联用户表中的主键ID) |
Access control can be carried out through these five tables. The specific operation steps are as follows:
User enters username and password to log in,
Judging from the user table, if the entered user name and password are illegal, jump back and log in again
If legal, return the user's ID number in the user table,
Through this user ID number, query the user's role ID number in the association table between the user and the role,
Get the role ID number, and use this ID number to query the association table between roles and nodes to find out the node access rights owned by this role,
Store all the permission nodes in SESSION. When the user accesses a certain module,
For example: http://www.lampbroher.net/index.php/stu/index
We use the permissions in the session to compare with $_GET['m'] and $_GET['a'],
If $_GET['m'] or $_GET['a'] does not exist in SESSION, it means that the user does not have this permission, just handle it.
Reference code:
RBAC class file:
/*+-------------------------------------------------- ----------------------------------------+
| RBAC permission control class
class Rbac{
private $node_tablename; //Define private attribute node table name
private $group_auth_tablename; //Define private attribute group permission table name
private $group_tablename; //Define private attribute user group table name
private $group_user_tablename; //Define private attribute user belonging group table name
private $user_tablename; //Define private attribute user table name
/*
Construction method
@param1 string node table name
@param2 string user permission table name
@param3 string user group table name
@param4 string user belonging group table name
@param5 string user table name
*/
public function __construct($node_tablename='node',$group_auth_tablename='group_auth',$group_tablename='group',$group_user_tablename='group_member',$user_tablename='member'){
$this->node_tablename = $node_tablename; //Get the node table name
$this->group_auth_tablename = $group_auth_tablename; //Get the user permission table name
$this->group_tablename = $group_tablename; //Get the user group table name
$this->group_user_tablename = $group_user_tablename; //Get the user belonging group table name
$this->user_tablename = $user_tablename; //Get the user table name
}
/*
Set node method
@param1 string node name
@param2 string node parent ID
@param2 string node Chinese description
@return int ID after successful insertion of node record
*/
public function set_node($name,$pid,$zh_name=''){
if(!empty($name) && !empty($pid)){
$node = D($this->node_tablename)->insert(array("name"=>$name,"pid"=>$pid,"zh_name"=>$zh_name));
}
return $node;
}
/*
How to set permissions
@param1 int group ID
@param2 int node ID
@return int ID after inserting permission record successfully
*/
public function set_auth($gid,$nid){
if(!empty($gid) && !empty($nid)){
$auth = D($this->group_auth_tablename)->insert(array("gid"=>$gid,"nid"=>$nid));
}
return $auth;
}
/*
Get node method
@param1 int node ID
@return array Get the relevant information of the node table
*/
public function get_node($id){
if(!empty($id)){
$data = D($this->node_tablename)->field("id,name,pid")->where(array('id'=>$id))->find();
return $data;
}else{
return false;
}
}
/*
How to obtain group permissions
@param1 int user group ID
@return array Get relevant information about the group permission table
*/
public function get_auth($gid){
if(!empty($gid)){
$data = D($this->group_auth_tablename)->field("nid")->where(array('gid'=>$gid))->select();
return $data;
}else{
return false;
}
}
/*
Get user group method
@param1 int user ID
@return array Get the user group id corresponding to the user
*/
public function get_group($uid){
if(!empty($uid)){
$data = D($this->group_user_tablename)->field("gid")->where(array('uid'=>$uid))->select();
return $data;
}else{
return false;
}
}
/*
Get the child node method of a node
@param1 int node ID
@return array Get all the child nodes corresponding to this node
*/
public function get_cnode($nid){
if(!empty($nid)){
$cnode = D($this->node_tablename)->field("name")->where(array('pid'=>$nid))->select();
return $cnode;
}else{
return false;
}
}
/*
How to obtain permission
@param1 int user ID
@return array Get the permission list
*/
public function get_access($uid){
if(!empty($uid)){
//Call the method to get group information
$group = $this->get_group($uid);
//Traverse group information
foreach($group as $v){
//Pass the group ID into the method to obtain permissions
$auth = $this->get_auth($v['gid']); //Get the permissions of the group
}
//Traverse the permission array of the group
foreach($auth as $val){
//Pass the ID of the node into the method of obtaining node information
$node[] = $this->get_node($val['nid']); //Get node-related information
}
//Traverse the node array and assemble it
foreach($node as $nval){
if($nval['pid']==0){
$fnode[] = $nval; //Push the controller into the fnode array
//$cnode = $this->get_cnode($nval['id']);
}else{
$cnode[] = $nval; //Push the controller method into the cnode array
}
}
//Assemble the controller array and the controller array into an array
foreach($fnode as $fval){
foreach($cnode as $cval){
if($cval['pid'] == $fval['id']){
$access[$fval['name']][] = $cval['name'];
}
}
}
//Return permission list array
return $access;
}else{
return false;
}
}
/*
How to check permissions
@param1 int user ID
@return boolean Whether permission is prohibited
*/
public function check($uid){
if(!empty($uid)){
//Save permissions into $_SESSION['Access_List']
$_SESSION['Access_List'] = $this->get_access($uid);
if(!empty($_GET['m'])){
//Determine whether this controller is allowed
if(array_key_exists($_GET['m'],$_SESSION['Access_List'])){
//Determine whether the method of this controller is allowed
if(in_array($_GET['a'],$_SESSION['Access_List'][$_GET['m']])){
//Return true if allowed
return true;
}else{
// Otherwise return false
return false;
}
}else{
return false;
}
}else{
return false;
}
}else{
//$_SESSION['user_'.$uid]['Access_List'] = 0;
return false;
}
}
public function show_node(){
$path = APP_PATH.'/controls/';
$handle = opendir($path);
while(false!==($data = readdir($handle))){
if(is_file($path.$data) && $data!='common.class.php' && $data!='pub.class.php'){
$controller = str_replace(".class.php",'',$data);
$res = fopen($path.$data,'r');
$str = fread($res,filesize($path.$data));
$pattern = '/function(.*)()/iU';
preg_match_all($pattern, $str, $matches);
foreach($matches[1] as $v){
$v = trim($v);
$arr[$controller][] = $v;
}
}
}
closedir($handle);
return $arr;
}
}
Initialization class:
/*+-------------------------------------------------- ----------------------------------------+
| Initialize controller
class Common extends Action {
/*
Initialization method
*/
public function init(){
//If SESSION is empty, jump
if(empty($_SESSION['user_login'])){
$this->redirect("pub/index");
}
$a = new rbac();
if(!$a->check($_SESSION['user_info']['id'])){
echo "<script>alert('You do not have this permission!')</script>";
exit("

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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,

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

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.
