通過 Apache 實現用戶認證

文章位置: 主頁 > 文章資料庫 > Linux / BSD > 通過 Apache 實現用戶認證
瀏覽次數: 20296
更新時間: 2005/05/31 20:22

建立 .htacces 檔案

基本(Basic) 驗證是目前最為廣泛使用的方法,以下例子會替 /var/www/html/dir_protect 加入密碼保護,請先在這目錄建立一個 .htaccess 的檔案,然後加入以下內容:

01 AuthName "Member Only"
02 AuthType Basic
03 AuthUserFile /var/www.html/dir_protect/.htpasswd
04 <Limit GET POST>
05 require valid-user
06 </Limit>


以上段落的意思為:

AuthName "Member Only" -- 密碼保錄目錄名稱,這裡可自行修改。
AuthType Basic -- 使用基本驗證方法。
AuthUserFile /var/www.html/dir_protect/.htpasswd -- 儲存登入帳號的檔案。
<Limit GET POST> -- 限制所有 GET 及 POST 方法。
require valid-user -- 合法使用者可以存取目錄。

建立 .htpasswd 檔案

下一步是建立 .htpasswd 檔案。因為 .htpasswd 檔案內每一行代表一組帳號,格式為:

username:password

但裡面的密碼是經過編碼的,所以不能直接編碼,需要使用 apache 內建的 htpasswd 來做,以下是建立方法:

01 touch /var/www.html/dir_protect/.htpasswd
02 htpasswd -m /var/www.html/dir_protect/.htpasswd auth_user
03 New password: 輸入密碼
04 Re-type new password: 再次輸入密碼確認


如果發目錄內加入了 .htaccess 及 .htpasswd 兩個檔案後未能有密碼保護功能,便需要編輯 apache 的 httpd.conf 檔案,並加入以下內容:

01 <Directory "/var/www/html/dir_protect">
02     AllowOverride All
03 </Directory>


P.S. AllowOverride All 代表可以在 .htaccess 檔案使用任何指令。
編輯好 httpd.conf 後需要重新啟動 apache。

使用 PHP 建立 .htpasswd

以上是通過 apache 內建的 htpasswd 程式來做,而使用 php 同樣可以做到,但在執行時請注意,apache 對 /var/www.html/dir_protect/.htpasswd 要有寫入權限,方法如下:

01 <?php
02 $username 
"admin";
03
$password "passwd";
04
05
// make password string
06
$crypt_str $username ":" crypt($newpass"MM");
07
08
$fp fopen("/var/www.html/dir_protect/.htpasswd""a+");
09
fputs($fp$crypt_str."\n");
10
fclose($fp);
11
?>


以上程式會建立 admin 帳號,密碼是 passwd。


====================================================
歡迎轉載,但轉載時請保留此宣告,不得作為商業用途
作者: Sam Tang <admin{at}phpini{dot}com>
來源網站: http://www.phpdc.com/


用戶評論 按這裡發表新評論 
herbert user at yourdomain dat com
10 August 2005 14:52
有沒方法可以和PHP 的log in page 整合, 只需log in 一次便能php 和Apache htacces 也收到 log in id and password 作驗証?
 
 
 發表評論
姓名:
Email:
內容: