Can .htpasswd have user groups and can PHP read them?

371 views Asked by At

if .htpasswd contains joe:password and .htaccess uses basic authentication and you log in as Joe, then $_SERVER['PHP_AUTH_USER'] / $_SERVER['REMOTE_USER'] / $_ENV['PHP_AUTH_USER'] / $_ENV['REMOTE_USER'] all become joe.

But what if you want your code to allow something just to a certain group?

i.e. Can you divide your users to groups right inside .htpasswd (e.g. accountant:joe:password), then have PHP grab the group?

1

There are 1 answers

1
Álvaro González On

The Apache module that can provide HTTP basic auth with file storage backend and group support is mod_authz_groupfile, but groups have to be defined in a separate file:

admins: amy bill
support: charlie david edward
guests: fernando ivonne

But I believe groups are something internal to Apache and they aren't exposed to PHP, let alone the browser. From the PHP standpoint, if you have physical access to data files, you always can get the information by yourself:

$rawGroups = file('/path/to/.htgroup');
$usersByGroup = [];
foreach ($rawGroups as $rawGroup) {
    if (!preg_match('/^\s*(?P<group>[\S]+)\s*:\s*(?P<users>.+)\s*$/', $rawGroup, $matches)) {
        continue;
    }
    $usersByGroup[$matches['group']] = preg_split('/\s+/', $matches['users']);
}

Demo

If you don't really need to have Apache involved, then just create your own homebrew group system.