Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing permissions in PHP

I've tried to do this several times with no luck. After reading this post, it made me interested in doing this again. So can anyone tell me why the following doesn't work?

<?php

$guest = 1;
$editor = 2;
$admin = 4;

$user = $editor;

if( $user == ($editor | $admin) ) {
    echo "Test";    
}

?>
like image 990
Kevin Avatar asked Aug 19 '08 23:08

Kevin


1 Answers

Use the bitwise OR operator (|) to set bits, use the AND operator (&) to check bits. Your code should look like this:

<?php

    $guest = 1;
    $editor = 2;
    $admin = 4;

    $user = $editor;

    if( $user & ($editor | $admin) ) {
        echo "Test";    
    }

?>

If you don't understand binary and exactly what the bitwise operators do, you should go learn it. You'll understand how to do this much better.

like image 74
Paige Ruten Avatar answered Nov 09 '22 18:11

Paige Ruten