安裝
pear install Auth_HTTP
# 或 Composer
composer require pear/auth_http
核心用法 (資料庫驅動)
require_once 'Auth/HTTP.php';
$options = [
'dsn' => 'mysql://user:pass@localhost/db', // PEAR DB DSN
'table' => 'users', // 用戶表
'usernamecol' => 'username', // 用戶名欄位
'passwordcol' => 'password', // 密碼欄位
'cryptType' => 'md5', // 密碼雜湊: md5, sha1, plain 等
'db_fields' => '*', // 額外欄位 (* 全部)
];
$auth = new Auth_HTTP('DB', $options);
$auth->setRealm('Admin Area'); // Realm 名稱 (瀏覽器彈窗顯示)
$auth->setCancelText('Access Denied'); // 取消/失敗提示
$auth->start(); // 開始認證流程 (輸出 Header、驗證、失敗則 exit)
if ($auth->getAuth()) {
// 認證成功
$username = $auth->getUsername();
$extra = $auth->getAuthData(); // 取得 db_fields 所有欄位
echo "Welcome, $username! Your email: {$extra['email']}";
}
支援的儲存驅動
| 驅動 | 說明 | DSN 範例 |
| DB | PEAR DB 抽象層 (需安裝 DB) | `mysql://u:p@host/db` |
| MDB2 | PEAR MDB2 (較新) | `mysqli://u:p@host/db` |
| File | 檔案型 (htpasswd 格式) | `/path/to/.htpasswd` |
| LDAP | LDAP 目錄服務 | `ldap://host:389/dc=example,dc=com` |
| POP3/IMAP | 郵件伺服器帳號驗證 | `pop3://host:110` |
| RADIUS | RADIUS 協議 | `radius://host:1812/secret` |
| SAP | SAP 系統 | 專用參數 |
進階:自定義驗證邏輯 (繼承 Auth_Container)
class MyAuth extends Auth_Container {
public function fetchData($username, $password) {
// 任意邏輯:呼叫 API、檢查 Redis、多因子驗證...
$user = MyUserModel::findByUsername($username);
if ($user && password_verify($password, $user->password_hash)) {
$this->authData = $user->toArray(); // 供 getAuthData() 使用
return true;
}
return false;
}
}
$auth = new Auth_HTTP('MyAuth', []); // 無需 DSN
$auth->start();
Digest 認證 (比 Basic 安全,密碼不以明文傳輸)
$options['digest'] = true; // 啟用 Digest
// 需在資料庫儲存 HA1 = md5("$username:$realm:$password")
// 或由 Auth_HTTP 自動計算 (需存明文或可逆加密,不推薦)
// 最佳實踐:資料庫存 password_hash (bcrypt/argon2),僅用 Basic + HTTPS
常見問題
- **瀏覽器彈窗醜/無法自定義 UI** → HTTP Auth 本質限制,需改用表單登入 + Session/JWT。
- **登出無效** → 瀏覽器快取憑證,需關閉瀏覽器或發送 `WWW-Authenticate` 配合 401 強制重新驗證 (體驗差)。
- **CGI/FastCGI 環境 `$_SERVER['PHP_AUTH_USER']` 為空** → Apache 需 `SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0`,Nginx 需 `fastcgi_param HTTP_AUTHORIZATION $http_authorization;`。
適用場景
- 內部管理後台、API 簡易保護、開發環境快速加鎖。
- **不適合** 公開網站前台 (體驗差、無登出、無 CSRF 保護、無記住我)。
- 上一篇文章: PEAR 安裝與環境配置全攻略:include_path 設定、go-pear、Composer 共存
- 下一篇文章: PEAR 常用套件速查表:12 大分類、30+ 核心套件功能與現代替代方案
Copyright ©
程式碼之家 All Rights Reserved