Skip to content

Instantly share code, notes, and snippets.

@hungtrinh
Created April 10, 2018 07:00
Show Gist options
  • Save hungtrinh/a1cfefb2c0f5995359dbb915a5be1e9f to your computer and use it in GitHub Desktop.
Save hungtrinh/a1cfefb2c0f5995359dbb915a5be1e9f to your computer and use it in GitHub Desktop.
Check permission using bitwise operators
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