Asked  8 Months ago    Answers:  5   Viewed   46 times

I am working on a user-role / permission system in PHP for a script.

Below is a code using a bitmask method for permissions that I found on phpbuilder.com.

Below that part is a much simpler version w3hich could do basicly the same thing without the bit part.

Many people have recommended using bit operators and such for settings and other things in PHP, I have never understood why though. In the code below is there ANY benefit from using the first code instead of the second?

<?php
/**
 * Correct the variables stored in array.
 * @param    integer    $mask Integer of the bit
 * @return    array
 */
function bitMask($mask = 0) {
    $return = array();
    while ($mask > 0) {
        for($i = 0, $n = 0; $i <= $mask; $i = 1 * pow(2, $n), $n++) {
            $end = $i;
        }
        $return[] = $end;
        $mask = $mask - $end;
    }
    sort($return);
    return $return;
}


define('PERMISSION_DENIED', 0);
define('PERMISSION_READ', 1);
define('PERMISSION_ADD',  2);
define('PERMISSION_UPDATE', 4);
define('PERMISSION_DELETE', 8);

//run function
// this value would be pulled from a user's setting mysql table
$_ARR_permission = bitMask('5');

if(in_array(PERMISSION_READ, $_ARR_permission)) {
    echo 'Access granted.';
}else {
    echo 'Access denied.';
}
?>

non-bit version

<?PHP
/*
   NON bitwise method
*/

// this value would be pulled from a user's setting mysql table
$user_permission_level = 4;

if($user_permission_level === 4) {
    echo 'Access granted.';
}else {
    echo 'Access denied.';
}

?>

 Answers

75

Why not just do this...

define('PERMISSION_DENIED', 0);
define('PERMISSION_READ', 1);
define('PERMISSION_ADD',  2);
define('PERMISSION_UPDATE', 4);
define('PERMISSION_DELETE', 8);

//run function
// this value would be pulled from a user's setting mysql table
$_ARR_permission = 5;

if($_ARR_permission & PERMISSION_READ) {
    echo 'Access granted.';
}else {
    echo 'Access denied.';
}

You can also create lots of arbitrary combinations of permissions if you use bits...

$read_only = PERMISSION_READ;
$read_delete = PERMISSION_READ | PERMISSION_DELETE;
$full_rights = PERMISSION_DENIED | PERMISSION_READ | PERMISSION_ADD | PERMISSION_UPDATE | PERMISSION_DELETE;

//manipulating permissions is easy...
$myrights = PERMISSION_READ;
$myrights |= PERMISSION_UPDATE;    // add Update permission to my rights
Wednesday, March 31, 2021
 
nasty
answered 8 Months ago
47

I studied around the webs and come out with my own zerofill function, base on the explanation given. This method works for my program.

Have a look:

function zeroFill($a,$b) {
    if ($a >= 0) { 
        return bindec(decbin($a>>$b)); //simply right shift for positive number
    }

    $bin = decbin($a>>$b);

    $bin = substr($bin, $b); // zero fill on the left side

    $o = bindec($bin);
    return $o;
}
Wednesday, March 31, 2021
 
muncherelli
answered 8 Months ago
19

MVC allows you to separate your business logic from your presentation layer. This "Separation of Concerns" allows you to quickly find and edit portions of your code. It also enables easy reuse of your UI components across your system.

Check out the wiki page for a overly academic and technical introduction to MVC http://en.wikipedia.org/wiki/Model_view_controller

Saturday, May 29, 2021
 
LOKESH
answered 5 Months ago
73

Exceptions allow you to distinguish between different types of errors, and is also great for routing. For example...

class Application
{
    public function run()
    {
        try {
            // Start her up!!
        } catch (Exception $e) {
            // If Ajax request, send back status and message
            if ($this->getRequest()->isAjax()) {
                return Application_Json::encode(array(
                    'status' => 'error',
                    'msg'    => $e->getMessage());
            }

            // ...otherwise, just throw error
            throw $e;
        }
    }
}

The thrown exception can then be handled by a custom error handler.

Since PHP is a loosely typed language, you might need to ensure that only strings are passed as arguments to a class method. For example...

class StringsOnly
{
    public function onlyPassStringToThisMethod($string)
    {
        if (!is_string($string)) {
            throw new InvalidArgumentException('$string is definitely not a string');
        }

        // Cool string manipulation...

        return $this;
    }
}

...or if you need to handle different types of exceptions in different ways.

class DifferentExceptionsForDifferentFolks
{
    public function catchMeIfYouCan()
    {
        try {
            $this->flyForFree();
        } catch (CantFlyForFreeException $e) {
            $this->alertAuthorities();
            return 'Sorry, you can't fly for free dude. It just don't work that way!';
        } catch (DbException $e) {
            // Get DB debug info
            $this->logDbDebugInfo();
            return 'Could not access database. What did you mess up this time?';
        } catch (Exception $e) {
            $this->logMiscException($e);
            return 'I catch all exceptions for which you did not account!';
        }
    }
}

If using transactions in something like Zend Framework:

class CreditCardController extends Zend_Controller_Action
{
    public function buyforgirlfriendAction()
    {
        try {
            $this->getDb()->beginTransaction();

            $this->insertGift($giftName, $giftPrice, $giftWowFactor);

            $this->getDb()->commit();
        } catch (Exception $e) {
            // Error encountered, rollback changes
            $this->getDb()->rollBack();

            // Re-throw exception, allow ErrorController forward
            throw $e;
        }
    }
}
Saturday, May 29, 2021
 
Bharanikumar
answered 5 Months ago
50

You could use it for bitmasks to encode combinations of things. Basically, it works by giving each bit a meaning, so if you have 00000000, each bit represents something, in addition to being a single decimal number as well. Let's say I have some preferences for users I want to store, but my database is very limited in terms of storage. I could simply store the decimal number and derive from this, which preferences are selected, e.g. 9 is 2^3 + 2^0 is 00001001, so the user has preference 1 and preference 4.

 00000000 Meaning       Bin Dec    | Examples
 ???????? Preference 1  2^0   1    | Pref 1+2   is Dec   3 is 00000011
 ???????? Preference 2  2^1   2    | Pref 1+8   is Dec 129 is 10000001
 ???????? Preference 3  2^2   4    | Pref 3,4+6 is Dec  44 is 00101100
 ???????? Preference 4  2^3   8    | all Prefs  is Dec 255 is 11111111
 ???????? Preference 5  2^4  16    |
 ???????? Preference 6  2^5  32    | etc ...
 ???????? Preference 7  2^6  64    |
 ???????? Preference 8  2^7 128    |

Further reading

  • http://www.weberdev.com/get_example-3809.html
  • http://stu.mp/2004/06/a-quick-bitmask-howto-for-programmers.html
  • Why should I use bitwise/bitmask in PHP?
  • http://en.wikipedia.org/wiki/Mask_%28computing%29
Wednesday, June 16, 2021
 
edorian
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share