PHP?的?HTTP?認證機制僅在 PHP 以?Apache?模塊方式運行時才有效,因此該功能不適用于 CGI 版本。在 Apache 模塊的 PHP 腳本中,可以用?header()?函數(shù)來向客戶端瀏覽器發(fā)送“Authentication Required”信息,使其彈出一個用戶名/密碼輸入窗口。當(dāng)用戶輸入用戶名和密碼后,包含有 URL 的 PHP 腳本將會加上預(yù)定義變量PHP_AUTH_USER,PHP_AUTH_PW?和?AUTH_TYPE?被再次調(diào)用,這三個變量分別被設(shè)定為用戶名,密碼和認證類型。預(yù)定義變量保存在?$_SERVER?或者$HTTP_SERVER_VARS?數(shù)組中。支持“Basic”和“Digest”(自 PHP 5.1.0 起)認證方法。
Note:?PHP 版本問題
Autoglobals?全局變量,包括?$_SERVER等,自 PHP?4.1.0?起有效,$HTTP_SERVER_VARS?從 PHP 3 開始有效。
以下是在頁面上強迫客戶端認證的腳本范例:
Example #1 Basic HTTP 認證范例
<?php if (!isset($_SERVER['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'; exit; } else { echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>"; echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>"; } ?>
在瀏覽器地址欄輸入腳本在服務(wù)器位置,彈出如下輸入框:
如果點擊取消的話輸出:
Text to send if user hits Cancel Button
如果輸入用戶名和密碼,點擊登錄:
Hello hello.
You entered world as your password.
Example #2 Digest HTTP 認證范例
本例演示怎樣實現(xiàn)一個簡單的 Digest HTTP 認證腳本。
<?php $realm = 'Restricted area'; //user => password $users = array('admin' => 'mypass', 'guest' => 'guest'); if (empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="'.$realm. '" qop="auth" nonce="'.uniqid().'" opaque="'.md5($realm).'"'); die('Text to send if user hits Cancel button'); } // analyze the PHP_AUTH_DIGEST variable if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) die('Wrong Credentials!'); // generate the valid response $A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]); $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']); $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2); if ($data['response'] != $valid_response) die('Wrong Credentials!'); // ok, valid username & password echo 'Your are logged in as: ' . $data['username']; // function to parse the http auth header function http_digest_parse($txt) { // protect against missing data $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1); $data = array(); preg_match_all('@(\w+)=([\'"]?)([a-zA-Z0-9=./\_-]+)\2@', $txt, $matches, PREG_SET_ORDER); foreach ($matches as $m) { $data[$m[1]] = $m[3]; unset($needed_parts[$m[1]]); } return $needed_parts ? false : $data; } ?>
Note: 兼容性問題
在編寫 HTTP 標(biāo)頭代碼時請格外小心。為了對所有的客戶端保證兼容性,關(guān)鍵字“Basic”的第一個字母必須大寫為“B”,分界字符串必須用雙引號(不是單引號)引用;并且在標(biāo)頭行 HTTP/1.0 401 中,在 401 前必須有且僅有一個空格。
在以上例子中,僅僅只打印出了 PHP_AUTH_USER 和 PHP_AUTH_PW 的值,但在實際運用中,可能需要對用戶名和密碼的合法性進行檢查。或許進行數(shù)據(jù)庫的查詢,或許從 dbm 文件中檢索。
注意有些 Internet Explorer 瀏覽器本身有問題。它對標(biāo)頭的順序顯得似乎有點吹毛求疵。目前看來在發(fā)送 HTTP/1.0 401 之前先發(fā)送 WWW-Authenticate 標(biāo)頭似乎可以解決此問題。
自 PHP 4.3.0 起,為了防止有人通過編寫腳本來從用傳統(tǒng)外部機制認證的頁面上獲取密碼,當(dāng)外部認證對特定頁面有效,并且安全模式被開啟時,PHP_AUTH 變量將不會被設(shè)置。但無論如何,REMOTE_USER 可以被用來辨認外部認證的用戶,因此可以用 $_SERVER['REMOTE_USER'] 變量。
Note: 配置說明
PHP 用是否有 AuthType 指令來判斷外部認證機制是否有效。
注意,這仍然不能防止有人通過未認證的 URL 來從同一服務(wù)器上認證的 URL 上偷取密碼。
Netscape Navigator 和 Internet Explorer 瀏覽器都會在收到 401 的服務(wù)端返回信息時清空所有的本地瀏覽器整個域的 Windows 認證緩存。這能夠有效的注銷一個用戶,并迫使他們重新輸入他們的用戶名和密碼。有些人用這種方法來使登錄狀態(tài)“過期”,或者作為“注銷”按鈕的響應(yīng)行為。
Example #3 強迫重新輸入用戶名和密碼的 HTTP 認證的范例
<?php function authenticate() { header('WWW-Authenticate: Basic realm="Test Authentication System"'); header('HTTP/1.0 401 Unauthorized'); echo "You must enter a valid login ID and password to access this resource\n"; exit; } if (!isset($_SERVER['PHP_AUTH_USER']) || ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) { authenticate(); } else { echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br />"; echo "Old: {$_REQUEST['OldAuth']}"; echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>\n"; echo "<input type='hidden' name='SeenBefore' value='1' />\n"; echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' />\n"; echo "<input type='submit' value='Re Authenticate' />\n"; echo "</form></p>\n"; }
該行為對于 HTTP 的 Basic 認證標(biāo)準(zhǔn)來說并不是必須的,因此不能依靠這種方法。對 Lynx 瀏覽器的測試表明 Lynx 在收到 401 的服務(wù)端返回信息時不會清空認證文件,因此只要對認證文件的檢查要求沒有變化,只要用戶點擊“后退”按鈕,再點擊“前進”按鈕,其原有資源仍然能夠被訪問。不過,用戶可以通過按“_”鍵來清空他們的認證信息。
同時請注意,在 PHP 4.3.3 之前,由于微軟 IIS 的限制,HTTP 認證無法工作在 IIS 服務(wù)器的 CGI 模式下。為了能夠使其在 PHP 4.3.3 以上版本能夠工作,需要編輯 IIS 的設(shè)置“目錄安全”。點擊“編輯”并且只選擇“匿名訪問”,其它所有的復(fù)選框都應(yīng)該留空。
另一個限制是在 IIS 的 ISAPI 模式下使用 PHP 4 的時候,無法使用?PHP_AUTH_*?變量,而只能使用?HTTP_AUTHORIZATION。例如,考慮如下代碼:list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));。
Note:?IIS 注意事項
要 HTTP 認證能夠在 IIS 下工作,PHP 配置選項?cgi.rfc2616_headers?必須設(shè)置成?0(默認值)。
Note:
如果安全模式被激活,腳本的 UID 會被加到?WWW-Authenticate?標(biāo)頭的?realm?部分。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
