The following small series for everyone to bring a piece of PHP clever use of bit operations to achieve site rights management methods. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
First we define 4 constants to set four kinds of permissions:
=====================================
Define (add,1);//increase permissions on database records
Define (upd,2);//Modify permissions for database records
Define (sel,4);//find permissions for database records
Define (del,8);//delete permissions for database records
=====================================
Next, assume that there are 3 users:
A user has Add-upd-sel-del four permissions, using a bitwise OR operation to calculate the total value of A's permissions
$a _all=add| upd| sel| del;//$all =15 can notice that this value is the same as the result of the addition.
b The user has add-upd-sel three permissions, using a bitwise OR operation to calculate the total value of the privilege of B
$b _all=add| upd| sel;//$all =7 The result of this value and addition is the same.
C User has add-upd two permissions, use bit or operation to calculate C's privilege value
$c _all=add| upd;//$all =3 The result of this value and addition is the same.
=====================================
Next we use the bit and do the arithmetic
$a _all&add results are true
$a _all&upd results are true
$a _all&sel results are true
$a _all&del results are true
=====================================
$b _all&add results are true
$b _all&upd results are true
$b _all&sel results are true
$b _all&del result is False
=====================================
$c _all&add results are true
$c _all&upd results are true
$c _all&sel result is False
$c _all&del result is False
=====================================
Did you find the secret?
1, when the total value of the privilege and does not have the right to do bit and operation, the result is false
2, the value of the permission is 2 of the second party
The
knows that this two-point privilege is easier to handle, as long as the user's current privilege value and the permissions required by the current operation are bitwise and calculated each time the permission operation is performed. If the result is true, do it for false error handling (not necessarily the times are wrong, you can design your own program without permission).