Re: Bitwise operations criticism needed
| From: | Gerard Samuel | Date: | Tue, 31 Aug 2004 14:28:36 +0000 |
| Subject: | Re: Bitwise operations criticism needed | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-195287@lists.php.net to get a copy of this message | ||
Marek Kilimajer wrote:
Gerard Samuel wrote:Yes I may use it some day. I was trying to simulate an illegal permission. So how should I handle this, if I should handle this???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;9 is 1001, so if you ignore fourth bit, it's equal to 1. Some day you might want to add other permission rights using other bits.$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??
Ok, I understand what you mean about the if() statement, as its related to your previous comment above. But isn't $compare = $perm_total & $user_perm; needed for this to work?$user['whats_his_face'] = 6; // rw // Set the sum of "source" permissions foreach($perm as $value) {These 2 pieces of code:$perm_total |= $value;} echo "<ul>"; // Loop over the users foreach($user as $id => $user_perm) {and// User permissions should be between 1 & 7, else set it to 0 if ($user_perm > $perm_total || $user_perm < 0) { $user_perm = 0; }do the same thing, and are quite useless, the code will work without it. If you extend the rights one day, you would have to modify it.// 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 --