views:

61

answers:

3

I'm developping a site for fun and I'm trying to implement a directory access control based on bitwise operators.
I've defined GUEST = 1, GROUP1 = 15 and GROUP2 = 23

If I compare

echo (23 & 1); // print 1 

but if I define GUEST, GROUP1 and GROUP2:

define('GUEST', 1);  
define('GROUP1', 15);  
define('GROUP2', 23);  
// and then  
echo (GROUP2 & GUEST); // print 0  
echo USER_GUEST.','.USER_ROLES1.','.USER_ROLES2; // print 1,15,23` 

With GROUP1 no problem:

echo (GROUP1 & GUEST); print 1.  

Where do I'm wrong ? some suggestion ? Thanks.


I've discovered something really strange: my GUEST, GROUP1 and GROUP2 are declared inside an ini file which I parse by a function parse_ini_file(self::$fileName, true); within a class . After I've parsed the file I define recursively the couples key=value defined under section [DEFINE] (a simply trick). If I comment there my GROUP2=23 definition and I declare it inside the current script (GROUP2 & GUEST) return 1!

A: 

PHP 5.3:

php > define('GUEST', 1);
php > define('GROUP1', 15);
php > define('GROUP2', 23);
php > echo GROUP2 & GUEST;
1
php > echo GROUP1 & GUEST;
1

What PHP version are you using?


Artefacto pointed out a possible string issue (e: but appears to have retracted his post, hm). Again in 5.3:

php > var_export(GUEST);
1
php > var_export(GROUP1);
15
php > var_export(GROUP2);
23
php > define('GUEST_AS_STRING', '1');
php > var_export(GUEST_AS_STRING);
'1'
php > echo GROUP1 & GUEST_AS_STRING;
1
php > echo GROUP2 & GUEST_AS_STRING;
1

'1' is character 49. 49 & 15 is 1, but 49 & 23 is 17. I'm not convinced that this is a string issue...

Charles
I was googling to find some information. Version installed on the test server is PHP Version 5.2.9. At this moment I can't test it on different version
cantabria
+1  A: 

Make sure you use base 2 numbers for your groups, i.e. 1,2,34,8,16,32.... or you can step on each other. Here's the correct way to do permissions in a bitfield.

define('GUEST', 1);  
define('GROUP1', 2);  
define('GROUP2', 4);
$groups |= GUEST;
$groups |= GROUP1;
if($groups & GUEST) {
    // This user is a guest (it is)
}
if($groups & GROUP1) {
    // This user is in group 1 (it is)
}
if($groups & GROUP2) {
    // This user is in group 2 (it is NOT)
}
Matt Williamson
Michael Mrozek
Yeah, I missed what he was saying.
Matt Williamson
A: 

Solved.
I completely misunderstood a declaration in php manual where in Changelog they say:

5.2.4 Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals.

It's absolutly clear: keys and section name ... not values!
The parse_ini_file() function evaluates integers values as PHP string even if they aren't enclosed in double quotes. This is pity, but so it is ;-)

Thanks for your collaboration

cantabria