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!

2
  • 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. Commented Feb 27, 2013 at 19:22
  • According to stackoverflow.com/questions/132194/… it's usually not a good idea to store objects in $_SESSION. Commented Feb 27, 2013 at 19:39

2 Answers 2

5

It should probably be

const GUEST = 1; // 1 const USER = 2; // 10 const MODERATOR = 8; // 1000 const ADMIN = 16; // 10000 
Sign up to request clarification or add additional context in comments.

2 Comments

And when a user is admin i have to add 10000 to the permission field in the database?
@user1362916 Do you know what are binary numbers?
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.