MySQL bit-manipulation and recovery in PHP

I am trying to optimize the mysql table a bit to have a slightly more manageable table. I would like to save user rights in the bit field.

For example, user permissions may be 0110 (my number of user permissions is growing, so the length of this may be slightly longer)

An example may correspond to the following:

0: User cannot post news on the website 1: User can post new articles on the website 1: User can edit any article on the website 0: User cannot delete articles from the website, etc. (for other permissions)

If I have this, this is stored in the mysql bit field. How can I manipulate this in PHP?

For example, in PHP there is an easy way to get the third bit and see if it is 0 or 1?

Is there an easy way to set the third bit to 0 or 1?

+3
source share
2 answers

You can use bitwise operators .

For instance:

$bits = bindec('0110');
var_dump($bits & bindec('0100'));

You will get "4" (i.e. a non-zero value, which you can consider as "ok"), since the third bit is set to $bits.

AND:

$bits = bindec('0010');
var_dump($bits & bindec('0100'));

You will get 0 - since the third bit is $bitsnot set.


Of course, you do not need to call every time bindec- I just used it here to simplify the reading; my first example can be rewritten somehow like this:

$bits = bindec('0110');
var_dump($bits & 1<<2);


, , ; :

define('PERMISSION_TO_DO_X', 1);
define('PERMISSION_TO_DO_Y', 1<<1);
define('PERMISSION_TO_DO_Z', 1<<2);

:

$bits = bindec('0110');
if ($bits & PERMISSION_TO_DO_X) {
    echo "OK to do X<br />";
}
if ($bits & PERMISSION_TO_DO_Y) {
    echo "OK to do Y<br />";
}
if ($bits & PERMISSION_TO_DO_Z) {
    echo "OK to do Z<br />";
}

:

OK to do Y
OK to do Z

:

  • 0 ( X )
  • ( ) 1: Y
  • ( ) 1: Z
+5

, (.. 1,2,4,8,16), . ,

:

if ($accessLevel & $userPermissions) 

,


, .

, . ( ), . :

Read - 1
Edit - 2
Create - 4
Delete - 8

, . , . , , :

$newUser->Permissions = Permissions::Read | Permissions::Create;

, , .

, , AND:

if ($newUser->Permissions & Permissions::Read) {
    echo 'You can do this!';
}  else {
    echo 'You can't this!';
}

, , , . .., , .

+7

Source: https://habr.com/ru/post/1726180/


All Articles