How to use PHP for HTTP authentication

Source: Internet
Author: User
Tags http authentication
The HTTP authentication mechanism of PHP is only valid when PHP runs in the Apache module mode. Therefore, this function is not applicable to CGI versions. In the PHP script of the Apache module, you can use the header () function to send the "AuthenticationRequired" message to the client browser to bring up a user name/password input window.

The HTTP authentication mechanism of PHP is only valid when PHP runs in the Apache module mode. Therefore, this function is not applicable to CGI versions. In the PHP script of the Apache module, you can use the header () function to send the "Authentication Required" message to the client browser to bring up a user name/password input window. After the user enters the user name and password, the pre-defined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE will be added to the PHP script containing the URL. these three variables are set as user names respectively, password and authentication type. The predefined variables are stored in the $ _ SERVER or $ HTTP_SERVER_VARS array. Supports "Basic" and "Digest" (from PHP 5.1.0) authentication methods. For more information, see the header () function.

Note:PHP version problemsAutoglobals global variables, including $ _ SERVER, etc., from PHP? Effective from 4.1.0, $ HTTP_SERVER_VARS effective from PHP 3.

The following is an example of a script that forces client authentication on the page:

Example #1 Basic HTTP authentication

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"

Hello {$ _ SERVER ['php _ AUTH_USER ']}.

";
Echo"

You entered {$ _ SERVER ['php _ AUTH_PW ']} as your password.

";
}
?>


Example #2 Example of Digest HTTP authentication

This example shows how to implement a simple Digest HTTP authentication script. For more information, see? RFC 2617.

$ Realm = 'restricted region ';

// 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 ['uris ']);
$ 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, 'URL' => 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;
}
?>


 

 
Compatibility problems

Compile the HTTP
Be careful when using the header code. To ensure compatibility with all clients, the first letter of the keyword "Basic" must be capitalized as "B", and the demarcation string must be referenced in double quotation marks (not single quotation marks ).
HTTP/1.0 401 In 401 There must be only one space before.

 

 
In the preceding example, only PHP_AUTH_USER And
PHP_AUTH_PW
But in practice, you may need to check the validity of the user name and password. The database may be queried, or retrieved from the dbm file.
 

 
Note that some Internet Explorer
The browser itself has a problem. It seems a bit picky about the order of headers. Currently
HTTP/1.0 401 Sent before
WWW-Authenticate The header seems to solve this problem.
 

 
From PHP 4.3.0
To prevent users from getting passwords from pages authenticated by the traditional external mechanism by writing scripts, when the external authentication is effective for a specific page and & safemode; is enabled, PHP_AUTH
The variable will not be set. However, REMOTE_USER
Can be used to identify external authenticated users, so you can use
$ _ SERVER ['remote _ user'] Variable.
 

 
Configuration instructions

Is PHP available? AuthType Command to determine whether the external authentication mechanism is valid.

 

 
Note: This still prevents unauthorized URLs from stealing passwords from authenticated URLs on the same server.
 
 
Both Netscape Navigator and Internet Explorer receive 401
When the server returns the information of all local browsers, Windows
Authentication cache. This effectively cancels a user and forces them to re-enter their username and password. Some people use this method to "expire" the logon status or act as a response to the "logout" button.
 
 

Example of force-re-entering the user name and password for HTTP authentication

<br /><?php<br />&nbsp;&nbsp;function&nbsp;authenticate()&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;header('WWW-Authenticate:&nbsp;Basic&nbsp;realm="Test&nbsp;Authentication&nbsp;System"');<br />&nbsp;&nbsp;&nbsp;&nbsp;header('HTTP/1.0&nbsp;401&nbsp;Unauthorized');<br />&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;"You&nbsp;must&nbsp;enter&nbsp;a&nbsp;valid&nbsp;login&nbsp;ID&nbsp;and&nbsp;password&nbsp;to&nbsp;access&nbsp;this&nbsp;resource\n";<br />&nbsp;&nbsp;&nbsp;&nbsp;exit;<br />&nbsp;&nbsp;}<br /><br />&nbsp;&nbsp;if&nbsp;(!isset($_SERVER['PHP_AUTH_USER'])&nbsp;||<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;($_POST['SeenBefore']&nbsp;==&nbsp;1&nbsp;&&&nbsp;$_POST['OldAuth']&nbsp;==&nbsp;$_SERVER['PHP_AUTH_USER']))&nbsp;{<br />&nbsp;&nbsp;&nbsp;authenticate();<br />&nbsp;&nbsp;}<br />&nbsp;&nbsp;else&nbsp;{<br />&nbsp;&nbsp;&nbsp;echo&nbsp;"<p>Welcome:&nbsp;{$_SERVER['PHP_AUTH_USER']}<br&nbsp;/>";<br />&nbsp;&nbsp;&nbsp;echo&nbsp;"Old:&nbsp;{$_REQUEST['OldAuth']}";<br />&nbsp;&nbsp;&nbsp;echo&nbsp;"</p>\n";<br />&nbsp;&nbsp;} <p><br /></p><p>该行为对于 HTTP 的 Basic 认证标准来说并不是必须的,因此不能依靠这种方法。对 Lynx 浏览器的测试表明 Lynx 在收到 401 的服务端返回信息时不会清空认证文件,因此只要对认证文件的检查要求没有变化,只要用户点击“后退”按钮,再点击“前进”按钮,其原有资源仍然能够被访问。不过,用户可以通过按“_”键来清空他们的认证信息。</p><p>同时请注意,在 PHP 4.3.3 之前,由于微软 IIS 的限制,HTTP 认证无法工作在 IIS 服务器的 CGI 模式下。为了能够使其在 PHP 4.3.3 以上版本能够工作,需要编辑 IIS 的设置“目录安全”。点击“编辑”并且只选择“匿名访问”,其它所有的复选框都应该留空。</p><p>另一个限制是在 IIS 的 ISAPI 模式下使用 PHP 4 的时候,无法使用 <i>PHP_AUTH_*</i> 变量,而只能使用 <i>HTTP_AUTHORIZATION</i>。例如,考虑如下代码:<i>list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));</i>。</p><blockquote><p><b>Note</b>: <b>IIS 注意事项</b> 要 HTTP 认证能够在 IIS 下工作,PHP 配置选项 cgi.rfc2616_headers 必须设置成 <i>0</i>(默认值)。 </p></blockquote><blockquote><p><b>Note</b>: 如果安全模式被激活,脚本的 UID 会被加到 <i>WWW-Authenticate</i> 标头的 <i>realm</i> 部分。</p></blockquote><hr />

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.