Bitwise operations criticism needed
| From: | Gerard Samuel | Date: | Tue, 31 Aug 2004 08:09:30 +0000 |
| Subject: | Bitwise operations criticism needed | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-195251@lists.php.net to get a copy of this message | ||
The situation.
Im currently using a home brewed groups permission code in my site,
but for limited users/groups its ok. Beyond that, the code will take the fast road to hell.
I started to look in depth at bitwise operations today,
and after much googling, and looking at other code, came up with this
mock up, of a basic permissions routine (not neccessarilly the final product), that utilizes bitwise operations.
Im looking for advise, to see if Im heading in the right way, and/or improvements with this.
Thanks for your time...
-- start code --
<?php
$perm = $user = array();
$perm_total = 0;
// Permissions from some source like a database/file
$perm['execute'] = 1;
$perm['write'] = 2;
$perm['read'] = 4;// User permissions (predetermined) from sessions maybe
$user['tom'] = 7; // rwx $user['joe'] = 5; // rx $user['dirty_harry'] = 9; // illegal in this case??$user['whats_his_face'] = 6; // rw // Set the sum of "source" permissions foreach($perm as $value) {
$perm_total |= $value;} echo "<ul>"; // Loop over the users foreach($user as $id => $user_perm) {
// User permissions should be between 1 & 7, else set it to 0
if ($user_perm > $perm_total || $user_perm < 0)
{
$user_perm = 0;
}
// Compare user bits to permission bits
$compare = $perm_total & $user_perm;
// Make it an even 4 bit string (for visual effect)
$bits_string = sprintf("%03d", decbin( $compare ));
echo "<li>User: " . $id . "</li>";
// Check to see if the comparision contains any permission bits
$can_read = (($compare & $perm['read']) == $perm['read']) === TRUE ? "TRUE" : "FALSE";
$can_write = (($compare & $perm['write']) == $perm['write']) === TRUE ? "TRUE" : "FALSE";
$can_execute = (($compare & $perm['execute']) == $perm['execute']) === TRUE ? "TRUE" : "FALSE";
echo "<ul>";
echo "<li>" . $user_perm . ' -> ' . $bits_string . "</li>";
echo "<li>Can Read: $can_read</li>";
echo "<li>Can Write: $can_write</li>";
echo "<li>Can Execute: $can_execute</li>";
echo "</ul>";} echo "</ul>"; ?> -- end code --