In the process of writing an authentication process for my software, I came across the need for a permissions function. Basically, I wanted to use prime numbers to indicate a specified permission 'group' or 'category'. For example, the categories could be asigned a prime number as follows;
/* Categories */
2 - Blue
3 - Red
5 - Green
7 - Yellow
Then, a permission level can be assigned to a user as follows;
/* Permissions */
3 - Bob
10 - John
42 - Steve
210 - Mary
Using the prime number assigned to the specified category, you can specify access to each category by multiplying the allowed categories together. For example, Bob only has access to Red, whereas Steve has access to Red, Blue and Yellow.
Only prime numbers work because the resulting permission number can only be devided evenly by 1, itself, and one of the prime numbers. So, a script can be written to look for the multiples of the permission number. Here is what I came up with;
function get_perm($auth) {
/* initialize variables */
$perm = array();
$count = 0;
for ($x = 1; $x <= $auth; $x++) {
$result = $auth / $x;
if (!ereg("[.]", $result)) { // is whole number
$n = 0;
for ($y = 1; $y <= $x; $y++) {
$result = $x / $y;
if (!ereg("[.]", $result)) { // is whole number
$n++;
}
}
if ($n == 2) {
$count++;
$perm[$count] = $x;
}
}
}
return($perm);
}
The function starts by looking for multiples of $auth (the given authorization number [42]). Then it checks to see if that multiple is prime. If it is, the script inserts the value into array $perm.
When called, the function will return the array of permissions for the given authorization number. For example;
$auth = 42;
$perm = get_perm($auth);
$perm will now contain the numbers; 2, 3, 7 since 2*3*7=42. The values can be parsed by using a simple loop.
/* count number of permisions */
$count = count($perm);
/* print permisions */
while ($count > 0) {
echo "$perm[$count]<br>";
$count--;
}
If there is a more simple way to acheive the previous results, please feel free to comment (and e-mail me). I orignally thought PHP was able to do this simply by mod($auth). However, I was wrong.