1

im trying to learn to use bitwise permissions for in my application. Problem is, it's not working :(

When a user logs in, i save a user object in the session, which looks like this :

    [user] => User Object
    (
        [id] => 1
        [firstname] => Firstname
        [lastname] => Lastname
        [emailaddress] => email@adres
        [permissions] => 16
    )

i have a class called authenticate, in which i define some contants, which are these :

class authenticate {   

const GUEST = 1;  // 1
const USER = 10;  // 2
const MODERATOR = 1000; // 8
const ADMIN = 10000; // 16

Now when a user logs in in the admin, i want to make sure the user has admin rights, which i try to check this way :

  if ($_SESSION['user']->permissions & authenticate::ADMIN){
             echo 'yep admin';
  }else {
             echo 'no admin';
  }

When i have a user that does lets say have a number 8 as permission, its not an admin and it should say no admin.. but it doesn't it always says yep admin ..

could anyone tell me what i am doing wrong here?

Thanks!

user1362916
  • 119
  • 2
  • 14
  • 4
    Those... aren't bitwise. Those are decimal-wise. (Ten-wise?) Furthermore I don't think you aren't checking for bitwise permissions right — it should be `perm & required_perm === required_perm`. (Though maybe not.) PHP 5.4+ supports binary literal notation in the form `0b0101`. – Waleed Khan Feb 27 '13 at 19:22
  • According to http://stackoverflow.com/questions/132194/php-storing-objects-inside-the-session it's usually not a good idea to store objects in `$_SESSION`. – Mike Feb 27 '13 at 19:39

2 Answers2

5

It should probably be

const GUEST = 1;     // 1
const USER = 2;      // 10
const MODERATOR = 8; // 1000
const ADMIN = 16;    // 10000
Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
5

The problem, as Mikhail shows, is that 1000 is the number one-thousand. You need the number whose binary representation is 1000, which is the number eight.

You can use 1, 2, 4, 8, 16, etc., as Mikhail does.

However, if you want to visualise what's happening with the bitwise calculation, it's great if you can see where the bits are visually. PHP 5.4 introduced a binary integer syntax.

const GUEST     = 0b00001;  // 1
const USER      = 0b00010;  // 2
const MODERATOR = 0b01000;  // 8
const ADMIN     = 0b10000;  // 16
Community
  • 1
  • 1
lonesomeday
  • 233,373
  • 50
  • 316
  • 318