第二章. PHP3 的特色

目錄
HTTP 認證
處理影像
支援檔案上傳
支援 HTTP cookie
支援資料庫
正規運算(Regular expressions)
錯誤處理(Error handling)

HTTP 認証

PHP的HTTP認証只能在 Apache 模組下執行. 在 Apache 模組下, 我們可以用 Header()函式將"認証要求"送到客戶端的 遊覽器並出現一個要求客戶端輸入帳號和密碼的視窗. 當使用者輸入帳號和密碼后, 資料就會被送到$PHP_AUTH_USER, $PHP_AUTH_PW 和 $PHP_AUTH_TYPE等變數. 這三個變數代表的意思為使用者帳號,密碼和認証的型態.

Example 2-1. HTTP Authentication example

<?php   if(!isset($PHP_AUTH_USER)) {
     Header("WWW-Authenticate: Basic realm=\"My Realm\"");
     Header("HTTP/1.0 401 Unauthorized");
     echo "Text to send if user hits Cancel button\n";
     exit;
   } else {
     echo "Hello $PHP_AUTH_USER.<P>";
     echo "You entered $PHP_AUTH_PW as your password.<P>";
   }
 ?>      

如果你是用 Internet Explorer browsers ,則送出標頭的順序需要格外僅慎. 先送WWW-Authenticate 標頭再送 HTTP/1.0 401 標頭是目前較好的做法.

In order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page. In this case, the $REMOTE_USER variable can be used to identify the externally-authenticated user.

Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.

Both Netscape and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource (as long as the credential requirements haven't changed).

Also note that this does not work using Microsoft's IIS server and the CGI version of PHP due to a limitation of IIS.