简体   繁体   中英

Comparing flags with bitwise operators

I am designing a permissions system that determines whether a user can access a page based on the flags set in his/her permissions field. Here's how I had thought to do this:

// 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);

I'm wondering if there is a more elegant/common way to do this. Is it possible to directly compare $required_permissions and $admin->permissions using some combination of bitwise operators that will yield false only if $required_permissions contains a 1 and the corresponding bit in $admin->permissions does not? Or is this rather repetitive function the best way?

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

This works even for no permissions needed: 0 & whatever == 0 is true.

To explain the bits somewhat

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM