The following small series will bring you a PHP method that uses bitwise operations to manage website permissions. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the following small series to bring you a PHP clever use of bit operations to achieve website permission management methods. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian.
First, we define four constants to set four permissions:
============================================
Define (ADD, 1); // ADD the database record permission
Define (UPD, 2); // modify database record permissions
Define (SEL, 4); // permission for searching database records
Define (DEL, 8); // permission for deleting database records
============================================
Assume that there are three users:
A user has four permissions for the ADD-UPD-SEL-DEL, using A bit or operation to calculate the total permissions of
$ A_all = ADD | UPD | SEL | DEL; // $ all = 15 you can note that the value and the result of the addition method are the same.
B user has three permissions for ADD-UPD-SEL, with a bit or calculation of B's total permissions
$ B _all = ADD | UPD | SEL; // $ all = 7 the addition result is the same.
C user has two permissions for ADD-UPD, calculate the total permissions of C with a bit or operation
$ C_all = ADD | UPD; // $ all = 3. the value and addition result are the same.
============================================
Next we use bitwise AND for calculation
$ A_all & ADD returns true
$ A_all & UPD returns true
$ A_all & SEL returns true
$ A_all & DEL returns true
============================================
$ B _all & ADD returns true
$ B _all & UPD: The result is true.
$ B _all & SEL returns true
$ B _all & DEL: The result is false.
============================================
$ C_all & ADD returns true
$ C_all & UPD returns true
$ C_all & SEL results are false
$ C_all & DEL: The result is false.
============================================
Discover the mysteries?
1. when the total number of permissions and the permissions that are not available are bitwise and computed, the result is false.
2. the permission value is the power of 2.
It becomes easy to understand the processing of these two permissions, as long as the user's current total permission value and the permissions required for the current operation are bitwise and computed each time a permission operation is executed. If the result is true, you only need to handle false errors (of course, you can design programs without permission ).
The above is a detailed description of PHP's clever use of bitwise operations to implement website permission management. For more information, see other related articles in the first PHP community!