首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 解析 .htgroup 文件類:Apache 群組授權管理

     編輯:PHP 綜合知識

前言

.htgroup 定義 Apache 基礎認證的用戶群組,格式為 groupname: user1 user2 ...。配合 .htpasswd 實現基於角色的存取控制(RBAC)。本文提供完整的 PHP 管理類。

.htgroup 文件格式

admin: user2
editor: user1 user3
writer: user3

完整類實現

file = $file;
        } else {
            throw new InvalidArgumentException("$file doesn't exist.");
        }
    }

    /** 讀取並解析群組文件 */
    private function read(): array {
        $groups = [];
        $lines = file($this->file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line) || $line[0] === '#') continue; // 支援註釋
            
            $parts = explode(': ', $line, 2);
            if (count($parts) === 2) {
                $group = $parts[0];
                $users = array_map('trim', explode(' ', $parts[1]));
                $users = array_filter($users); // 移除空值
                $groups[$group] = array_values($users);
            }
        }
        return $groups;
    }

    /** 寫入群組文件 */
    private function write(array $groups): void {
        $lines = [];
        foreach ($groups as $group => $users) {
            $lines[] = "$group: " . implode(' ', $users);
        }
        file_put_contents($this->file, implode("\n", $lines) . "\n", LOCK_EX);
    }

    /** 將用戶加入群組 */
    public function addUserToGroup(string $username, string $group): bool {
        if (empty($username) || empty($group)) return false;
        
        $all = $this->read();
        if (!isset($all[$group])) {
            $all[$group] = [];
        }
        if (!in_array($username, $all[$group], true)) {
            $all[$group][] = $username;
            $this->write($all);
            return true;
        }
        return false; // 已在群組中
    }

    /** 從群組移除用戶 */
    public function deleteUserFromGroup(string $username, string $group): bool {
        $all = $this->read();
        if (!isset($all[$group])) return false;
        
        $key = array_search($username, $all[$group], true);
        if ($key !== false) {
            unset($all[$group][$key]);
            $all[$group] = array_values($all[$group]); // 重建索引
            
            // 群組為空則刪除群組
            if (empty($all[$group])) {
                unset($all[$group]);
            }
            $this->write($all);
            return true;
        }
        return false;
    }

    /** 獲取用戶所屬群組 */
    public function getUserGroups(string $username): array {
        $all = $this->read();
        $groups = [];
        foreach ($all as $group => $users) {
            if (in_array($username, $users, true)) {
                $groups[] = $group;
            }
        }
        return $groups;
    }

    /** 獲取群組成員列表 */
    public function getGroupMembers(string $group): array {
        $all = $this->read();
        return $all[$group] ?? [];
    }

    /** 列出所有群組 */
    public function listGroups(): array {
        return array_keys($this->read());
    }
}

使用範例

addUserToGroup('alice', 'admin');
$handler->addUserToGroup('bob', 'editor');
$handler->addUserToGroup('charlie', 'editor');

// 查詢群組成員
print_r($handler->getGroupMembers('editor'));
// Array ( [0] => bob [1] => charlie )

// 查詢用戶群組
print_r($handler->getUserGroups('alice'));
// Array ( [0] => admin )

// 移除用戶
$handler->deleteUserFromGroup('bob', 'editor');

// 列出所有群組
print_r($handler->listGroups());

Apache 配置範例


    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/apache2/.htpasswd
    AuthGroupFile /etc/apache2/.htgroup
    Require group admin editor

進階:整合 .htpasswd + .htgroup 完整認證類

htpasswd = new Htpasswd($passwdFile);
        $this->htgroup = new Htgroup($groupFile);
    }

    /** 完整登入驗證:密碼正確 + 可選群組授權 */
    public function authenticate(string $username, string $password, array $requiredGroups = []): bool {
        if (!$this->htpasswd->verifyPassword($username, $password)) {
            return false;
        }
        if (empty($requiredGroups)) return true;
        
        $userGroups = $this->htgroup->getUserGroups($username);
        return !empty(array_intersect($requiredGroups, $userGroups));
    }

    /** 創建用戶並分配群組 */
    public function createUser(string $username, string $password, array $groups = []): bool {
        if (!$this->htpasswd->addUser($username, $password)) return false;
        foreach ($groups as $group) {
            $this->htgroup->addUserToGroup($username, $group);
        }
        return true;
    }

    /** 刪除用戶及其所有群組關係 */
    public function deleteUser(string $username): void {
        $this->htpasswd->deleteUser($username);
        foreach ($this->htgroup->getUserGroups($username) as $group) {
            $this->htgroup->deleteUserFromGroup($username, $group);
        }
    }
}

現代化建議

  • 資料庫替代文件:用戶/群組關係用資料庫表存儲,支援事務、索引、複雜查詢
  • RBAC 模型:角色-權限分離,比簡單群組更靈活
  • 應用層授權:Apache 模組侷限性大,現代架構多在 PHP 中間件/策略類處理授權
  • LDAP/SSO 整合:企業環境對接 Active Directory、Keycloak、Auth0

總結

Htgroup 類提供了 .htgroup 文件的完整管理功能,配合 Htpasswd 可實現基於 Apache 的用戶群組授權。理解其文件格式與操作邏輯,有助於維護傳統系統、或向現代認證架構遷移時做數據同步。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved