Heres a sample of a easy
৺permission management system.
The code isn't perfect, but still does its work ;-)
First, the "Permissions" Class
Class Permissions{
static
$Permissions = array(); static $Level = 1;
function AddLevel($Level){
self::$Permissions[strval(self::$Level)] = $Level; self::$Level = self::$Level<<1;
}
function CheckPermission($Has, $Need){
return ($Has & $Need)? true : false;
}
function DumpLevels(){
Foreach (self::$Permissions AS $Level=>$Permission){
echo "Level ":$Level.": ".$Permission."<br />";
}
}
function DumpPermissions($Level){
echo "Level ".$Level." :<br />";
Foreach (self::$Permissions AS $sLevel=>$Permission){
echo (self::CheckPermission($Level, $sLevel))? " - ".$Permission."<br />": "";
}
}
}
its an static class, so you can
৺access it easy at every time.
First, set up the desired
৺security levels:
$Permissions = new Permissions();
$Permissions->AddLevel("Read");
$Permissions->AddLevel("Write");
$Permissions->AddLevel("Execute");
If you use the DumpLevels() function like this
$Permissions->DumpLevels();
You will get this:
Level 1: Read
Level 2: Write
Level 4: Execute
To check if a user has the "needed" permissions, simple call the CheckPermission-Function like that:
$UsersLevel = 3;
$NeededLevel = 4;
$Permissions->CheckPermission($UsersLevel,$NeededLevel) //returns false
If you want to use "more" levels, you simple can use the "ShiftLeft"-Operator to check permissions of (root)levels:
$UsersLevel = 1<<8; // 2^8 = 256
$NeededLevel = 256;
$Permissions->CheckPermission($UsersLevel,$NeededLevel) //returns true
You can also dump the permissions a user with a known level has:
$UsersLevel = 3;
$Permissions->DumpPermissions($UsersLevel);
this returns:
Level 3 :
- Read
- Write
Look Behind the Engine:
How it works? Well, as you can see, i'm using bit-operaters here.
Each Base in the Binary-System represents a root-level of the permissions:
1 2 4 8 16 ...
f.e. the level 4 will be
100
You can get unique levels by simple adding the root-levels:
2 + 4 = 6 ->
110
A user having the level 6 will have
৺access to the areas, needing
৺security-level 2 OR 4
The
৺permission check is done by bitwise
AND-Operation (comparing MSB to MSB and so on...) :
Checking the needed level 4 (100) and the userlevel 6 (110) will result in "true":
100
110
____
100
100 > 0 so the result will be true.
Checking the needed level 3 (011) and the userlevel 4(100) will result in "false":
011
100
____
000
0 == 0 so the result will be false.