Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set permissions in binary

Tags:

php

I saw in school a system that set permissions using binary string.

Let's say 101001 = 41

So :

  • 1 can be permission to page 1
  • 2 can be permission to page 2
  • 4 can be permission to page 3
  • 8 can be permission to page 4
  • 16 can be permission to page 5
  • 32 can be permission to page 6

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.

like image 842
David Bélanger Avatar asked May 08 '12 19:05

David Bélanger


2 Answers

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.

like image 121
Mike B Avatar answered Oct 03 '22 08:10

Mike B


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.

like image 35
Denis Ermolin Avatar answered Oct 03 '22 08:10

Denis Ermolin