php 使用按位运算符检查权限

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 使用按位运算符检查权限相关的知识,希望对你有一定的参考价值。

Initially, I found bitmasking to be a confusing concept and found no use for it. So I've whipped up this code snippet in case anyone else is confused:

<?php

    // The various details a vehicle can have
    $hasFourWheels = 1;
    $hasTwoWheels  = 2;
    $hasDoors      = 4;
    $hasRedColour  = 8;

    $bike          = $hasTwoWheels;
    $golfBuggy     = $hasFourWheels;
    $ford          = $hasFourWheels | $hasDoors;
    $ferrari       = $hasFourWheels | $hasDoors | $hasRedColour;

    $isBike        = $hasFourWheels & $bike; # False, because $bike doens't have four wheels
    $isGolfBuggy   = $hasFourWheels & $golfBuggy; # True, because $golfBuggy has four wheels
    $isFord        = $hasFourWheels & $ford; # True, because $ford $hasFourWheels

?>

And you can apply this to a lot of things, for example, security:

<?php

    // Security permissions:
    $writePost = 1;
    $readPost = 2;
    $deletePost = 4;
    $addUser = 8;
    $deleteUser = 16;
    
    // User groups:
    $administrator = $writePost | $readPosts | $deletePosts | $addUser | $deleteUser;
    $moderator = $readPost | $deletePost | $deleteUser;
    $writer = $writePost | $readPost;
    $guest = $readPost;

    // function to check for permission
    function checkPermission($user, $permission) {
        if($user & $permission) {
            return true;
        } else {
            return false;
        }
    }

    // Now we apply all of this!
    if(checkPermission($administrator, $deleteUser)) {
        deleteUser("Some User"); # This is executed because $administrator can $deleteUser
    }

?>

以上是关于php 使用按位运算符检查权限的主要内容,如果未能解决你的问题,请参考以下文章

利用按位运算符轻松管理权限

使用按位比较与权限模型忽略第一位

这个按位运算如何检查 2 的幂?

按位权限不起作用PHP

按位运算符PHP

PHP按位权限