php 权限管理 Permissions Using Bitwise

系统 2056 0

Permissions Using Bitwise

This will be a quick tutorial on how to use bitwise operators in PHP to create permissions control. Some of next tutorials will cover how to implement it in application and how to use database to store permissions for users. Now some basics.

 

Bitwise operators

Those are operators (`&`, `|`,  `^`, `~`, `>>` and `<<`) in PHP that convert your value to bites and then do their job. Here are some examples on those that we will use (`&`, `|` and `~`).

 

How do they work?

Their work is very simple. First they convert passed value to bits and then, depending on operator, check for set/non set bits. Let’s take for and example 4 bits integer (on 32 bit systems they are 32 bit integers but to simplify we will use 4 bits). Maximum value of that integer is 15.

Why?

Because 4 bit representation of 15 is 1111 and that are those 4 bits.

How do we get them?

Every bit has its position, right to left, starting from 0. That position is used as exponent for base 2 and then multiplied with value (0 or 1) on that position.  To make it more clearly we will convert 1010 to integer. Starting from right to left first number is 0 so we do . Then we have . Next we have and last we have . Then we make sum of those number we got .

Now that you know what are bits, we can go further.

 

And operator (`&`)

This operators looks for bits that are set in both arguments and returns them. Let’s say you have this

 

      echo 3 & 6;
    
 This would return 2.

 

Why?

Because if we make bit representation of those numbers like this

 
Integer 8 4 2 1
3 0 0 1 1
6 0 1 1 0
3 & 6 0 0 1 0

you can see that only bits from column two are set in both 3 and 6. Since `&` searches for bits that are set in `a` and `b`, bit under two is set and is returned.

If we'd have

 
Integer 8 4 2 1
11 1 0 1 1
14 1 1 1 0
11 & 14 1 0 1 0

it would return10 because bits under 2 and 8 are set. Sum of 2 and 8 is 10.

 

Or operator (`|`)

This operator looks for bits that are set (value is 1) either in `a` or in `b`. For example

      echo 3 | 6;
    

 would return 7 because if you look at our table bits 4, 2 and 1 have value of 1. Bit 8 has value if 0 in both of them and he is not set. When you make sum of 4, 2 and 1 you get 7.

      echo 11 | 14;
    

 would also return 15 because every bit is set in at least one of them. Bit 8 is set in both of them, 4 is set in 14, 2 is set in both of them and 1 is set in 11.

 

Not operator (`~`)

This operator just sets bits that are not set and unset bits that are set (1 goes to 0 and 0 goes to 1).

For example

      echo ~6;
    

 would return 9 because bits that are 1 now, are 0 and those that are 0, not are 1. If you look at our table bits 8 and 1 have value of 0 and they are not set. But bits 4 and 2 have value of 1 and they are unset. Now you have 1001 and that is 9. If we where using 32 bit integers then we would get -7.

Why?

Because 32 bit integer has 32 times 0 or 1. 32 bit representation of 6 would be 00000000000000000000000000000110 and when you make it inverse you get 11111111111111111111111111111001 which corresponds to -7.

 

Defining permissions

Now that you know how operators work, we can create our permissions control. We will use simple class with 4 constants defined to make it simpler (we could use normal constants but I intend to make it as much as possible object oriented).

This is class.

      class perm
{
    /**
     * Read constant.
     *
     * @var int
     */
    const READ              = 1;

    /**
     * Edit constant.
     *
     * @var int
     */
    const EDIT              = 2;

    /**
     * Publish constant.
     *
     * @var int
     */
    const PUBLISH           = 4;

    /**
     * Delete constant.
     *
     * @var int
     */
    const DELETE            = 8;
}
    

 

As you can see we have numbers like 1, 2, 4 and 8. There is no number like 3 or 5 or 6 because we are looking for number that have just one bit and that other number do not have. Just use number that are potency of 2 ( , , and so on).

Create user classes

Now we will use bitwise operators to make classes (not PHP classes, but classes like `Guest` or `Admin`).

This is code.

      <?php
$guest = perm::READ;
$editor = $guest | perm::EDIT;
$moderator = $editor | perm::PUBLISH;
$publisher = $moderator & ~perm::EDIT;
$admin = $moderator | perm::DELETE;
?>
    

 

As you can see, $guest can only read (permission 1). $editor can read and edit. We just extend previous role and add new features. If you'd have 20 permissions, you would not for each role write what he can and what he can not do, instead you would extend role witl lover permission and add/remove feature. $moderator can everything that can $guest and $editor and he can also publish. But $publisher can everything that $moderator can, except he can not edit. And last, $admin can all.

Let me explain how did we created those roles. If you remember, on start I explained those operators. READ permission has only one bit set and that is first bit. EDIT has also only one bit and that is second bit. When we use `|` operator then we extend those two permissions and have two bits set and those are first and second. Then we do the same for $moderator and add one more bit (third bit). On publisher we want to disable one permission. To do that we inver permission that we want to disable so that only bit that is set becones 0 and all other become 1. Then we use `&` operator and set all bits that are set in both numbers. Here is how it works (we'll work again with 4 bits and not 32).

Variable $moderator has value of 7 (0111). Constant perm::EDIT has value of 2 (0010). When we invert EDIT constant we have 1101. Now we use `&` and we set only those bits that both have. In our example those are first and third bit. As you can see we do not have second bit because it was removed and that role has no EDIT permission.

 

Check if user can

This is the most easier part. We just use if statement and `&` operator. If we would like to check if $publisher can publish we would do it like so.

      if ($publisher & perm::PUBLISH)
    echo 'Can';
else
    echo 'Can not';
    

 

This would print `Can`.

Ok, but why do we use `&` to check if user can or can not do that?

Well, it's simple logic. If you remember, every bit that is set in both of them is returned. If no bit where set, 0 is returned and if there where any bits set then some integer that is not 0 is returned. If you know how PHP compares, then you also know that 0 is evaluated as false and any non-zero number is evaluated as true . If you wish you can read my article about comparing in PHP .

 

Test all roles and permissions

This is small function that will test all roles and permissions.

      /**
 * Echoes permissions.
 *
 * @param array $roles Roles array
 * @param array $perms Permissions array
 */
function checkPerms($roles, $perms)
{
    foreach ($roles as $k => $v) {
        echo '<b>', $k, '</b><br />';
        foreach ($perms as $pk => $pv) {
            if ($v & $pv)
                echo '- can ', $pk, '<br />';
            else
                echo '- can not ', $pk, '<br />';
        }
        echo '<br />';
    }
}

$roles = array(
    'Guest'         => $guest,
    'Editor'        => $editor,
    'Moderator'     => $moderator,
    'Publisher'     => $publisher,
    'Administrator' => $admin
);

$perms = array(
    'read'      => perm::READ,
    'edit'      => perm::EDIT,
    'publish'   => perm::PUBLISH,
    'delete'    => perm::DELETE
);

checkPerms($roles, $perms);
    

 

Result that is generated is like this.
      
        Guest
      
      
- can read
- can not edit
- can not publish
- can not delete


      
        Editor
      
      
- can read
- can edit
- can not publish
- can not delete


      
        Moderator
      
      
- can read
- can edit
- can publish
- can not delete


      
        Publisher
      
      
- can read
- can not edit
- can publish
- can not delete


      
        Administrator
      
      
- can read
- can edit
- can publish
- can delete
    

Thank you for reading. You dan download source code here .

 

form: http://www.php4every1.com/tutorials/create-permissions-using-bitwise-operators-in-php/

php 权限管理 Permissions Using Bitwise


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论