Skip to content
Jabran Rafique

Using Special Integers with Bitwise Operators for PHP RBAC

2 minutes read

I've been working on a project with a custom content management system (CMS), and part of it was a role-based access control (RBAC) system. Each role is built from permissions such as create, modify, remove and read-only.

The first approach I thought of came from a book I read a couple of years ago, PHP and MySQL Create Modify Reuse from Wrox Press. It uses bitwise operations to give a role one or more permissions. That book was probably what first got me interested in binary.

I had more than 12 permissions to hand out across roles, so I wanted the list of special integers ready. I wrote this small PHP function and ran it in the browser to print them.

/\*\*

- Converts the integer to binary and outputs list of integers that are power of 2
- @param: Integer
- @return: String
  \*/


    function get_special_binary( $decimal ) {
      $binaries = '';
      for ( $i = 1; $i < $decimal; $i++ ) {
      	$special_num = pow(2, $i);
      	$value = str_pad(base_convert($special_num, 10, 2), 8, '0', STR_PAD_LEFT);
        $binaries .= $special_num . " = " . substr($value, 0, 4) . " " . substr($value, 4) . '<br>';
      }
      return $binaries;
    }

It's on GitHub Gist if it's useful to you.

What are special integers?

They're powers of 2: 2, 4, 8, 16 and so on. In binary each of them has exactly one "1", which is what makes them useful with bitwise operators. You can see it in the list below for 1, 2, 4, 8 and 16.

1 – 0000 0001
2 – 0000 0010
3 – 0000 0011
4 – 0000 0100
5 – 0000 0101
6 – 0000 0110
7 – 0000 0111
8 – 0000 1000
9 – 0000 1001
10 – 0000 1010
11 – 0000 1011
12 – 0000 1100
13 – 0000 1101
14 – 0000 1110
15 – 0000 1111
16 – 0001 0000

Because no two of them share a bit, combining them with bitwise AND and OR gives results you can always pull apart again. For example:

0000 0001 — 1
AND
0000 0010 — 2

results

0000 0000 = 0

while:

0000 0001 — 1
OR
0000 0010 — 2

results

0000 0011 = 3

OR combines permissions into one number, and AND checks whether a given permission is in it.