我建议将权限(权限)转换为二进制状态字符串,然后将其作为长整数或十六进制字符串(VARCHAR;用于存储大量权限)存储在数据库中。
例子
$privileges_list = array(
0 => 'create_file',
1 => 'read_file',
2 => 'update_file',
3 => 'delete_file',
4 => 'create_pool',
5 => 'vote_in_pool',
6 => 'create_gallery',
7 => 'upload_images',
8 => 'view_statistics'
);
因此,如果您想为用户设置create file、update file 和view statistics 权限,只需将 1 放在字符串 (0, 2, 8) 中的适当位置,将其余位置设置为 0
$binary_string = "100000101";
这个字符串的最后一个字符是位置 0,第一个是位置 8。
现在您可以将此字符串转换为整数 (261) 或十六进制数 (105) 并将其作为该用户的权限集放入数据库中(我更喜欢十六进制)。
要将此值转换回权限列表,您可以使用类似这样的东西
function hexvalue2privileges($hexvalue, $plist) {
$res = array(); $res_assoc = array();
for ($i = strlen($hexvalue) - 1; $i >= 0; $i--) {
$bin = str_pad(decbin(hexdec(substr($hexvalue, $i, 1))), 4, '0', STR_PAD_LEFT);
$bin_array = array_reverse(str_split($bin, 1));
foreach ($bin_array as $bitstate) $res[] = $bitstate == '1' ? true : false;
}
foreach ($plist as $key => $id) {
$res_assoc[$id] = $res[$key];
}
return $res_assoc;
}
并调用此函数
print_r(hexvalue2privileges('105', $privileges_list));
输出将是
Array
(
[create_file] => 1 // true
[read_file] => // false
[update_file] => 1 // true
[delete_file] => // false
[create_pool] => // false
[vote_in_pool] => // false
[create_gallery] => // false
[upload_images] => // false
[view_statistics] => 1 // true
)
对于每个十六进制字符,您可以存储 4 个权限,因此使用此公式计算所需的字符数
$chars_needed = floor((count($privileges_list)-1) / 4) + 1; // result 3
获取二进制字符串的总长度
$binary_length = $chars_needed * 4; // result 12
固定权限集的长度
$binary_string = "100000101";
$binary_string = str_pad($binary_string, $binary_length, '0', STR_PAD_LEFT);
// result '000100000101'
将 $binary_string 转换为十六进制
$binary_string = "000100000101";
$hexvalue = "";
$groups = str_split($binary_string, 4);
foreach ($groups as $group) $hexvalue .= dechex(bindec($group));
// result $hexvalue='105' (1=0001, 0=0000, 5=0101)
您还可以通过为每个组(管理员、版主、访客、vip 等)创建权限集来创建权限组并将它们分配给用户。
希望对你有帮助