PHP BitWise Permissions&角色或替代品

时间:2012-11-20 17:14:40

标签: php permissions bit-manipulation bit user-permissions

我正在做第一个包含多个用户的权限和角色的应用。 我的理解是使用BitWise格式化的最佳方法。这是真的,还是有更好的选择?

这是我目前的测试代码,并且我得到了相当古怪的效果。 如果有人能够解释为什么会发生这种情况,那将非常感激。

示例:

$user = array('permissions' => 1); // This *should* return ONLY READ, (except it shows all)
$user = array('permissions' => 8); // Shows correct, FULL resources.

您可以使用它来测试代码...... http://writecodeonline.com/php/

define("PERM_R", 1);  # Read    
define("PERM_W", 2);  # Write   
define("PERM_E", 4);  # Edit    
define("PERM_D", 8);  # Delete  

define("ROLE_GUEST",  PERM_R);
define("ROLE_EDITOR", ROLE_GUEST | PERM_W | PERM_E);
define("ROLE_FULL",   ROLE_EDITOR | PERM_D);

function hasAccess($user, $action) {
    if( is_array($user) ) {
        return $user['permissions'] & $action;
    } else if ( is_int($user) ) {
        return $user & $action;
    }
}


$user = array('permissions' => 1);
echo "USER PERMISSIONS: ". $user['permissions'] ."<br /><br />";

# TEST PERMS
if(hasAccess($user, PERM_R)) {
    echo PERM_R;
    echo " - Yes you can see READ <br />";
}
if(hasAccess($user, PERM_R | PERM_W)) {
    echo PERM_R | PERM_W;
    echo " - Yes you can see READ & WRITE<br />";
}
if(hasAccess($user, PERM_R | PERM_W | PERM_E)) {
    echo PERM_R | PERM_W | PERM_E;
    echo " - Yes you can see READ & WRITE & EDIT<br />";
}
if(hasAccess($user, PERM_R | PERM_W | PERM_E | PERM_D)) {
    echo PERM_R | PERM_W | PERM_E | PERM_D;
    echo " - Yes you can see READ & WRITE & EDIT & DELETE<br />";
}

# TEST ROLES
if(hasAccess($user, ROLE_GUEST)) {
    echo ROLE_GUEST;
    echo " - Yes, You Are A GUEST <br />";
}
if(hasAccess($user, ROLE_EDITOR)) {
    echo ROLE_EDITOR;
    echo " - Yes, You Are A EDITOR <br />";
}
if(hasAccess($user, ROLE_FULL)) {
    echo ROLE_FULL;
    echo " - Yes, You Are A FULL <br />";
}

1 个答案:

答案 0 :(得分:1)

问题是,您只是返回按位&的结果,对于所有测试,该结果至少为1/true,因为所有用户都拥有R权限。

  1. 仅向hasAccess()提供一项权限,停止使用|
  2. 编写一个新函数以确定进行整数比较的用户级别。