Created
March 22, 2019 18:25
-
-
Save Kcko/f7483e3e26d448646934e328ea054be4 to your computer and use it in GitHub Desktop.
Check permission using bitwise operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Initially, I found bitmasking to be a confusing concept and found no use for it. So I've whipped up this code snippet in case anyone else is confused: | |
<?php | |
// The various details a vehicle can have | |
$hasFourWheels = 1; | |
$hasTwoWheels = 2; | |
$hasDoors = 4; | |
$hasRedColour = 8; | |
$bike = $hasTwoWheels; | |
$golfBuggy = $hasFourWheels; | |
$ford = $hasFourWheels | $hasDoors; | |
$ferrari = $hasFourWheels | $hasDoors | $hasRedColour; | |
$isBike = $hasFourWheels & $bike; # False, because $bike doens't have four wheels | |
$isGolfBuggy = $hasFourWheels & $golfBuggy; # True, because $golfBuggy has four wheels | |
$isFord = $hasFourWheels & $ford; # True, because $ford $hasFourWheels | |
?> | |
And you can apply this to a lot of things, for example, security: | |
<?php | |
// Security permissions: | |
$writePost = 1; | |
$readPost = 2; | |
$deletePost = 4; | |
$addUser = 8; | |
$deleteUser = 16; | |
// User groups: | |
$administrator = $writePost | $readPosts | $deletePosts | $addUser | $deleteUser; | |
$moderator = $readPost | $deletePost | $deleteUser; | |
$writer = $writePost | $readPost; | |
$guest = $readPost; | |
// function to check for permission | |
function checkPermission($user, $permission) { | |
if($user & $permission) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
// Now we apply all of this! | |
if(checkPermission($administrator, $deleteUser)) { | |
deleteUser("Some User"); # This is executed because $administrator can $deleteUser | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment