search
HomeBackend DevelopmentPHP TutorialCross-membership permission control based on native PHP_PHP tutorial

Based on native PHP cross-membership permission control

For a website's backend management system, a single super administrator authority often cannot meet our needs. Especially for large websites, this single authority will cause many problems.
For example: a website editor is usually only responsible for announcement updates of the company website, but if the website background does not have strict permission restrictions, he will be able to operate some of the customer's information. This is a big hidden danger.
If you have studied the ThinkPHP framework, you must know that there is something called RBAC. Today we will not talk about that, but let’s talk about how to implement cross permission control in the native PHP language.
Okay, not much to say, as usual, just talk about the principles and code.
There are many ways to implement cross-control of permissions. Here is just one idea: (I use the binary number method)
1. Here we first mention the operation methods of bitwise AND and bitwise OR:
1. Bitwise AND operator (&)
The two data participating in the operation are ANDed according to the binary bits. ("AND" operation => Whether there is a contained value such as: 7&8=0)
Operation rules: 0&0=0; 0&1=0; 1&0=0; 1&1=1;
That is: if both bits are "1" at the same time, the result is "1", otherwise it is 0
For example: 3&5 is 0000 0011 & 0000 0101 = 0000 0001 Therefore, 3&5 is worth 1.
In addition, negative numbers participate in bitwise AND operations in two's complement form.
2. Bitwise OR operator (|)
The two objects participating in the operation perform an "OR" operation based on binary bits. ("OR" operation => can include values ​​such as: 7=4|2|1, use "XOR" to remove included values ​​such as: 7^2)
Operation rules: 0|0=0; 0|1=1; 1|0=1; 1|1=1;
That is: as long as one of the two objects participating in the operation is 1, its value is 1.
For example: 3|5 that is 0000 0011 | 0000 0101 = 0000 0111 Therefore, 3|5 is worth 7.
In addition, negative numbers participate in bitwise OR operations in two's complement form.
After understanding the operations of bitwise AND and bitwise OR, let’s look at the following example:
Copy code
1
2 define('ADD',1);//Binary 1
3 define('DELETE',2);//Binary 10
4 define('UPDATE',4);//Binary 100
5 define('SELECT',8);//Binary 1000
6
7 //With permission it is 1, if there is no permission it is 0
8 $admin=ADD|DELETE|UPDATE|SELECT;//1111
9 $editor=ADD|UPDATE|SELECT;//1101
10 $user=SELECT;//1000
11 ?>
Copy code
I made four permissions for addition, deletion, modification and search respectively and set them as constants
The binary number of 1 is 1, the binary number of 2 is 10, the binary number of 4 is 100, and the binary number of 8 is 1000. This just becomes a rule
Some friends may ask where the 1111, 1101, and 1000 corresponding to the above permission variables admin, editor, and user come from?
There is a function in PHP to convert decimal numbers to binary numbers called decbin()
The following is the corresponding function explanation:
Copy code
decbin
(PHP 3, PHP 4, PHP 5)
decbin -- convert decimal to binary
Description
string decbin (int number)
Returns a string containing the binary representation of the given number parameter. The maximum value that can be converted is 4294967295 in decimal, which results in a string of 32 ones.
Example 1. decbin() example
echo decbin(12) . "n";
echo decbin(26);
?>
The above example will output:
1100
11010
See bindec(), decoct(), dechex() and base_convert().
Copy code
Let’s test the output and see:
Copy code
1
2
3
4 define('ADD',1);//Binary 1
5 define('DELETE',2);//Binary 10
6 define('UPDATE',4);//Binary 100
7 define('SELECT',8);//Binary 1000
8
9 //If there is permission, it is 1, if there is no permission, it is 0
10 $admin=ADD|DELETE|UPDATE|SELECT;//1111 15
11 $editor=ADD|UPDATE|SELECT;//1101 13
12 $user=SELECT;//1000 8
13
14 echo decbin($admin)."
";
15 echo decbin($editor)."
";
16 echo decbin($user)."
";
17
18
19 ?>
Copy code
Output result:
Then we can use this operation to determine the permissions. 1 means there is permission, 0 means no permission
For example:
The authority of admin (super administrator) is to add, delete, modify, and check, which is 1111——>0000 1111
The editor (website editor) has the permissions to add, modify, and check, which is 1101——>0000 1101
user (ordinary user) only has browsing and query permissions, which is 1000——>0000 1000
Then we only need to perform bitwise AND operations on them to determine whether we have permission
For example: (Looking from back to front) Convert decimal (database storage type value) to binary and perform "AND" operation
Website editing permissions 0000 1101 (the decimal value of the permission is 13) & 0000 0010 (the deletion permission is 2 in decimal and converted to 10 in binary). Result: 0000 0000, which means no permissions
Try again
Normal user permissions 0000 1000 & 0000 0001 (adding permissions in decimal is 1 and binary is 1) Result: 0000 0000 also does not have permissions
Super administrator permissions 0000 1111 & 0000 1101 (website editing permissions) Result: 0000 1101, which means you have website editing permissions
Okay, let’s look at specific examples
I built a database with 2 tables in it
One is the user table:
gid represents the group id of the permission table
One is the permission table:
flag represents the permission to add, delete, modify and check, which can be defined according to your own needs
Basic configuration page: config.php
Copy code
1
2
3 define('HOST','localhost');
4 define('DBNAME','member');
5 define('USER', 'root');
6 define('PASS', '');
7
8
9 $link=@mysql_connect(HOST,USER,PASS) or die('Database connection failed');
10
11 mysql_select_db(DBNAME,$link);
12
13 define('ADD',1);//binary 1
14 define('DELETE',2);//Binary 10
15 define('UPDATE',4);//Binary 100
16 define('SELECT',8);//Binary 1000
17
18 //If there is permission, it is 1, if there is no permission, it is 0
19 $admin=ADD|DELETE|UPDATE|SELECT;//1111
20 $editor=ADD|UPDATE|SELECT;//1101
21 $user=SELECT;//1000
22 ?>
Copy code
Log in homepage: index.html
Copy code
1
 2
 3
 4    
 5     Document
 6
 7
 8    
 9         账号:
10         密码:
11            
12        
13
14
复制代码
提交页面:action.php
 
复制代码
 1
 2     
 3     require_once('config.php');
 4     $username=$_POST['username'];
 5     $password=$_POST['password'];
 6 
 7 
 8     $sql="select * from user as a,role as b where a.gid=b.gid 
 9     and a.username='$username' and password='$password'";
10 
11     $result=mysql_query($sql);
12     if($data=mysql_fetch_array($result)){
13         //账号验证通过,判断对应权限
14         //此处判断的是 是否具备删除权限 如:user数据库存储的值为8转二进制为1000 删除权限的值为2转二进制为0010 与运算0000 无权限
15         if($data['flag']&DELETE){
16             echo "你有删除权限";
17         }else{
18             echo "你没有删除权限";
19         }
20 
21     }else{
22         echo "错误账号密码";
23     }
24     
25 
26 ?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/862109.htmlTechArticle基于原生PHP交叉会员权限控制 对于一个网站的后台管理系统,单一的超级管理员权限往往不能满足我们的需求,尤其是对于大型网站而言,...
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
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function