将标志与按位运算符进行比较

时间:2014-01-30 19:16:54

标签: php bit-manipulation

我正在设计一个权限系统,用于确定用户是否可以根据他/她的权限字段中设置的标志访问页面。以下是我的想法:

// define constants for permissions
defined('CAN_ACCESS_ADMIN') ? null : define('CAN_ACCESS_ADMIN', 0x002);
defined('CAN_ACCESS_STORE') ? null : define('CAN_ACCESS_STORE', 0x004);
defined('CAN_ACCESS_POST')  ? null : define('CAN_ACCESS_POST',  0x008);
...etc

function area_requires_permission($admin_id, $required_permissions) {

    $admin = get_admin_by_id($admin_id);

    // is admin access required?
    if ( $required_permissions & CAN_ACCESS_ADMIN ) { 

        // does user have admin access?
        if ( !($admin->permissions & CAN_ACCESS_ADMIN) ) { 

            // if not redirect
            header("Location: index.php"); 
            exit();

        }
    }

    if ( $required_permissions & CAN_ACCESS_STORE ) {
        if ( !($admin->permissions & CAN_ACCESS_STORE) ) {

            header("Location: index.php");
            exit();

        }
    }

    ...etc

}

// include this on each page were certain permissions are required
area_requires_permission($_SESSION['admin_id'], CAN_ACCESS_STORE | CAN_ACCESS_POST);

我想知道是否有更优雅/普通的方法来做到这一点。如果$required_permissions包含{{1},则可以使用某些按位运算符组合直接比较$admin->permissionsfalse,只会产生$required_permissions 并且1中的相应位没有?或者这个相当重复的功能是最好的方式?

1 个答案:

答案 0 :(得分:2)

if( ($required_permissions & $admin->permissions) != $required_permissions){
   //disallow
}

即使没有所需的权限,这也是有效的:0 & whatever == 0是真的。

稍微解释这些位

0101 & 1111 = 0101 == 0101 (superadmin!)
0100 & 1011 = 0000 != 0100 (disallowed!)
0000 & 1010 = 0000 == 0000 (no permissions needed)