设为首页 收藏本站
查看: 287|回复: 0

[经验分享] php 权限管理 Permissions Using Bitwise

[复制链接]

尚未签到

发表于 2017-4-3 12:18:45 | 显示全部楼层 |阅读模式
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/

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-359580-1-1.html 上篇帖子: [转]Rolling cURL: PHP并发最佳实践 下篇帖子: php webservice最常用的方法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表