PHP bitwise permission


/ Published in: PHP
Save to your folder(s)

Usage:

define('PIRATE',bindec('0001')); // 1
define('NINJA',bindec('0010')); // 2
define('JEDI',bindec('0100')); // 4
define('ADMIN',bindec('1000')); // 8

$rpermit = array(PIRATE,JEDI); // Equivilent Flags '0101'

$jim['permission'] = ADMIN + JEDI; // 12
$joe['permission'] = ADMIN + NINJA; // 10
$jon['permission'] = PIRATE; // 1

var_dump(isPermitted($rpermit,$jim['permission']));
var_dump(isPermitted($rpermit,$joe['permission']));


Copy this code and paste it in your HTML
  1. <?php
  2. function isPermitted(Array $types, $userPermission) {
  3. $resourcePermission = array_reduce($types,create_function('$n,$m','$n += (int)$m; return $n;'), 0);
  4. return ($resourcePermission & (int)$userPermission)?true:false;
  5. }
  6. ?>

URL: http://www.litfuel.net/tutorials/bitwise.htm

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.