I am very interested in writing a class that will help me with different permissions for different users (ie. ACL class.) I have been researching for a great method and bitwise operation stuck out!
I found a good article How to write a permission system using bits and bitwise operations in PHP. The article explains How to handle permissions using bitwise operation.
The only thing that I am not sure on how to do is how to allow a user to write a comment but not post a thread.
so if the permission are set like so:
<?php
$perms = array(
'can_post' => 1,
'can_comment' => 2,
'can_edit' => 4,
'can_delete' => 8
);
$user_perms = 2;
//CONDITION #1
if ($user_perms & $perms['can_comment']) {
/* He/She has permission to do this */
} else {
/* He/She doesn't have permission */
}
//CONDITION #2
if ($user_perms & $perms['can_post']) {
/* He/She has permission to do this */
} else {
/* He/She doesn't have permission */
}
?>
so above CONDITION #1
show work fine and the comments should be allowed but //CONDITION #2
should not be allowed because The user does not have a permission to post!
My question, how to allow a user to only comment but not post? to post you will have '001' and to comment you will have '010'.
Once you have your $perms
array defined, you can actually create your own maps from it:
// can comment and post but not edit or delete:
$poster = $perms['can_post'] | $perms['can_comment'];
// can edit and delete, but not comment or post:
$janitor = $perms['can_delete'] | $perms['can_edit'];
You can combine any number of permissions with the |
operator to build permission values.