Why should I use bitwise/bitmask in PHP?

后端 未结 8 1932
时光取名叫无心
时光取名叫无心 2020-11-30 20:54

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.

B

8条回答
  •  悲&欢浪女
    2020-11-30 21:29

    problem of this is if PERMISSION_READ is a mask itself

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

    then for 0101 - $rightWeHave 0011 - $rightWeRequire

    it is access granted, which we probably do not want so it should be

    if (($rightWeHave & $rightWeRequire) == $rightWeRequire) {
    echo 'access granted';
    }
    

    so now for

    0101 0011

    result is

    0001 so access is not granted because it is not equal to 0011

    but for

    1101 0101

    it is ok as the result is 0101

提交回复
热议问题