Page 1 of 1

UNIX-like permission calculation

Posted: Thu Nov 19, 2009 1:03 pm
by martind
Hello out there! :) First, sorry for my english, I'm not good at explaining stuff like this in English.

I want to implement a permission-layer in my website. The plan is to add one field to the user-table, called "permissions". This field is a integer.

By using the same method as the UNIX-file permission, where:
1 = Execute
2 = Write
4 = Read

The permission number (e.g. 7) represents the permissions. By adding each permissions number to the total permission number, you get the permission number.
Say, I add four more permissions:
8 = Delete
16 = Do other stuff
32 = Yet another permission
64 = The last permission

You can calculate what permissions are granted if you have the permission number 85:
64 (The last permission), 16 (Do other stuff), 4 (read) and 1 (Execute) because: 64+16+4+1 = 85

However, I don't know HOW to extract the numbers 64+16+4+1 from 85.

How do I calculate the permissions? It has to be dynamic, so, say I call a function with the number "548" and it returns an array with the permissions (512, 32, 4)

Re: UNIX-like permission calculation

Posted: Thu Nov 19, 2009 1:07 pm
by iankent
I think you loop through the possible numbers backwards and subtract them if the number is big enough

i.e. if you start with 85 it must contain 64, so remove 64 which gives you 21. 21 can't contain 32 but does contain 16. subtract 16 and you're left with 5, 5 doesn't contain 8 but does contain 4, so subtract 4 and you're left with 1

hth

Re: UNIX-like permission calculation

Posted: Thu Nov 19, 2009 1:08 pm
by Christopher
PHP has bitwise operators. See the manual:

http://www.php.net/manual/en/language.o ... itwise.php

Re: UNIX-like permission calculation

Posted: Thu Nov 19, 2009 1:09 pm
by iankent
arborint wrote:PHP has bitwise operators. See the manual:

http://www.php.net/manual/en/language.o ... itwise.php
thats a better answer than mine lol :P i hate bitwise operators ;)

Re: UNIX-like permission calculation

Posted: Thu Nov 19, 2009 2:07 pm
by martind
I made this before I saw the answer about bitwise operators:

Code: Select all

function permissions($value=0)
{
    $arrReturn = array();
    
    while ($value > 0) {
        $power = 0;
        $exp = 0;
        while (pow(2,$exp) <= $value) {
            $exp++;
        }
        $exp = $exp - 1;
        $permission = pow(2,$exp);
        if ($value >= 1) {
            $arrReturn[] = $permission;
        }
        $value = $permission = $value-$permission;
        
    }
    return $arrReturn;
}
Can I make it perform better using bitwise operators?