【问题标题】:How to allow some permission and not other using a bitwise system?如何使用按位系统允许一些权限而不是其他权限?
【发布时间】:2015-01-31 05:30:07
【问题描述】:

我对编写一个可以帮助我为不同用户提供不同权限的类非常感兴趣(即 ACL 类。) 我一直在研究一种很好的方法,并且按位运算突出了!

我找到了一篇好文章How to write a permission system using bits and bitwise operations in PHP。文章解释了如何使用按位运算处理权限。

唯一我不知道该怎么做的是如何允许用户写评论但不发布线程。

所以如果权限是这样设置的:

<?php

    $perms = array(
        'can_post' => 1,
        'can_comment' => 2,
        'can_edit' => 4,
        'can_delete' => 8
    );


   $user_perms = 2;    

//CONDITION #1
if ($user_perms & $perms['can_comment']) {
    /* He/She has permission to do this */
} else {
    /* He/She doesn't have permission */
}


//CONDITION #2
if ($user_perms & $perms['can_post']) {
    /* He/She has permission to do this */
} else {
    /* He/She doesn't have permission */
}

?>

所以上面CONDITION #1 显示工作正常,应该允许cmets,但不应该允许//CONDITION #2,因为用户没有发布权限!

我的问题,如何允许用户只评论而不发帖?发帖你会得到“001”,评论你会得到“010”。

【问题讨论】:

    标签: php bit-manipulation acl bitwise-operators user-permissions


    【解决方案1】:

    一旦定义了$perms 数组,您实际上就可以从中创建自己的地图:

    // can comment and post but not edit or delete:
    $poster = $perms['can_post'] | $perms['can_comment'];
    
    // can edit and delete, but not comment or post:
    $janitor = $perms['can_delete'] | $perms['can_edit'];
    

    您可以将任意数量的权限与| 运算符组合以构建权限值。

    【讨论】:

    • 这适用于十进制数还是仅适用于二进制数?我没有看到上面的任何二进制操作?
    • @andrebruton 只有当每个权限都是 2 的幂时它才会起作用。也就是说,你可以有一些聪明,比如$perms['general_posting'] = 3; 拥有自动激活多个基本权限标志的权限。
    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多