I saw in school a system that set permissions using binary string.
Let's say 101001 = 41
So :
So let's say I got the above binary string (101001). I have access to page 1, 4 and 6.
How can I do this in PHP ? Let's say I got a field in MySQL named perms
stored in dec so 101001 will be 41. How can I know that 41 is equal to 1, 8 and 32 in PHP ?
Thanks.
Sounds like you're talking about bits and bit-wise operators. This easiest way to set this up is to define constants for every permission
const POST = 1;
const DELETE = 2;
const UPDATE = 4;
const READ = 8;
Once you have these defined it's easy to make comparisons using the bitwise operators:
$userValue = '1101';
if ($userValue & self::POST) {
echo 'Can Post';
}
if ($userValue & self::DELETE) {
echo 'Can Delete';
}
if ($userValue & self::UPDATE) {
echo 'Can Update';
}
if ($userValue & self::READ) {
echo 'Can Read';
}
This is how many of PHP's own constants work. If you've ever set the error reporting using something like E_ALL & E_DEPRECATED
you're actually working with binary numbers.
You can use & operator
and check against those flags.
$READ = 8;
$WRITE = 1;
$EXECUTE = 32;
$permissions = 41;
if ($permissions & $READ) {
// do smth
}
if ($permissions & $WRITE ) {
// do smth
}
if ($permissions & $EXECUTE ) {
// do smth
}
Let me explain it. If you have bits 1001 (9). You just check forth bit (1000) with 1001. You just multiply EVERY bit of $permissions variable and bit number. Result will be 1000. It's convertible to true
value. So you have flag here. If check third bit (0100) it will result in 0000 and it's false
value. So you haven't got permissions here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With