PHP-获取用户的组


PHP - Get the Group of a user

我是htaccess使用的初学者,我在谷歌上搜索了一个答案,但没有找到对我有利的东西。

我想做一些容易理解的事情(所以我相信有一个合适的方法来做),但不知道怎么做。

我有这3个文件:

.htaccess

AuthName "Restricted Area"
AuthType Basic 
AuthUserFile /path/.htpasswd
AuthGroupFile /path/.htgroups
require group intern
require group extern
require group test

.htpasswd

user1:xxx
user2:yyy
user3:zzz

.htgroups

group1:user1 user3
group2:user2

在php中,我想对该组进行测试。我会在一些组中有很多用户,我会添加和删除一些,所以我不想这样做:

if($_SERVER['PHP_AUTH_USER'] == 'user1' || $_SERVER['PHP_AUTH_USER'] == 'user2')

但是

if($group == 'group1')

你能帮我找到一个简单的方法来获得这个变量$group吗?

非常感谢

巴斯蒂安

在对php.net进行了一些研究后,我找到了一种在文件中匹配模式的方法(在.htgoups中),所以我使用这个函数来获取一组登录用户。

function getHtGroup(){
    $AuthGroupFile = file("/path/.htgroups");
    $user = $_SERVER['PHP_AUTH_USER'];
    foreach ($AuthGroupFile as $line_num => $line) {
        if(preg_match("/(.*):(.*)$user/", $line, $matches)){
            $group=$matches[1];
            break;
        }
    }
    return $group;
}

建立在BastienSander的答案之上。这两个函数将从.htaccess文件中获取htgroup文件路径,并获取一组用户。

function gethtgroupfilepath() {
  preg_match('/AuthGroupFile .*/i', file_get_contents('.htaccess'), $match);
  $htgroupfilepath = array_pop(preg_split('/AuthGroupFile /i', $match[0]));
  return($htgroupfilepath);
}
function gethtgroup(){
  $AuthGroupFile = file(gethtgroupfilepath());
  $user = $_SERVER['PHP_AUTH_USER'];
  foreach ($AuthGroupFile as $line_num => $line) {
    if(preg_match("/(.*):(.*)$user/", $line, $matches)){
      $group=$matches[1];
      break;
    }
  }
  return $group;
}