2

我正在做我的第一个应用程序,其中包含多个用户的权限和角色。我的理解是最好的方法是使用 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 />";
}
4

1 回答 1

1

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

  1. 只输入一个权限hasAccess(),停止使用|
  2. Write a new function to determine the user level that does an integer comparison.
于 2012-11-20T17:35:21.757 回答