Bit Permissions
There are a lot of instances where a program or script will need to work with multiple users. Most of the time, users will need to have certain permissions (for example, a normal user and an administrator).
Lot’s of developers feel the need to make a huge database table with all these “can_*” fields as the permissions. But there’s an easier (and cleaner) way of doing this. All it takes is one integer field in your table.
You can represent a bunch of “on/off” permissions using one number and bit operators. Let’s take the user example. We could have permissions for access to the ACP, posting, uploading and deleting. We just assign a bit value (1, 2, 4, 8, 16, 32 etc):
| Bit | Permission Name |
|---|---|
| 1 | is_admin |
| 2 | can_post |
| 4 | can_upload |
| 8 | can_delete |
In PHP, I’d just make an array:
’can_post’ => 2,
’can_upload’ => 4,
’can_delete’ => 8);
Now all you have to do is add up all the permissions that you want the user to have. Here are two examples:
| User | Permissions |
|---|---|
| Admin | 15 (1 + 2 + 4 + 8, all erms) |
| User | 6 (2 + 4, posting and uploading) |
So you have a final value, all you have to do is use bit operators to test if a user is allowed to do whatever you want. In PHP, you would use a single ampersand character (read here). Here is a couple of examples:
if($user['permissions'] & $perms['is_admin'])
// okay
// trying to post
if($user['permissions'] & $perms['can_post'])
// okay
// trying to upload
if($user['permissions'] & $perms['can_upload'])
// okay
The basic statement is test_against & test_with. The & operator checks for bits set in both the numbers on either side of it. So in a normal users permission of 6, the ‘can_delete’ bit of 8 is not found. Neither is the ‘is_admin’ bit of 1 found, so both of those are false.
It might be a little hard to grasp, but it saves a lot of hard work!
September 29th, 2004 at 7:34 pm
cool. simple, yet effective.
September 30th, 2004 at 5:35 pm
You never seize to amaze me Chris