Php performs HTTP authentication

Source: Internet
Author: User
Tags http authentication microsoft iis
PHP features: the HTTP authentication mechanism of PHP for HTTP authentication is only valid when PHP runs in 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.

Note: PHP version problems

Autoglobals global variables, including $ _ SERVER, are valid from PHP 4.1.0 and $ HTTP_SERVER_VARS is valid from PHP 3.

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

Example #1 Basic HTTP authentication

 Hello {$_SERVER['PHP_AUTH_USER']}.

"; echo "

You entered {$_SERVER['PHP_AUTH_PW']} as your password.

"; }?>

Enter the script on the server in the address bar of the browser. the following input box is displayed:

If you click cancel, the output is as follows:

Text to send if user hits Cancel Button

If you enter the user name and password, click log on:

Hello hello.

You entered world as your password.

Example #2 Example of Digest HTTP authentication

This example shows how to implement a simple Digest HTTP authentication script.

  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: Compatibility issues

Be careful when writing HTTP 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; in the header line HTTP/1.0 401, there must be only one space before 401.

In the preceding example, only the values of PHP_AUTH_USER and PHP_AUTH_PW are printed. However, in actual use, 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 browsers have problems. It seems a bit picky about the order of headers. It seems that sending the WWW-Authenticate header before sending HTTP/1.0 401 seems to solve this problem.

Since PHP 4.3.0, in order 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 the security mode is enabled, the PHP_AUTH variable will not be set. However, in any case, REMOTE_USER can be used to identify external authenticated users, so you can use the $ _ SERVER ['remote _ user'] variable.

Note: Configuration instructions

PHP uses the AuthType command to determine whether the external authentication mechanism is effective.

Note: This still prevents unauthorized URLs from stealing passwords from authenticated URLs on the same server.

Both Netscape Navigator and Internet Explorer clear the Windows Authentication cache of all local browsers in the entire domain when they receive messages from the 401 server. 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 #3 Example of HTTP authentication that forces the user name and password to be re-entered

 Welcome: {$_SERVER['PHP_AUTH_USER']}
"; echo "Old: {$_REQUEST['OldAuth']}"; echo "

\n"; }

This behavior is not necessary for the Basic authentication standard of HTTP, so you cannot rely on this method. Tests on the Lynx browser show that Lynx does not clear the authentication file when it receives the information returned by the 401 server. Therefore, as long as the check requirements for the authentication file remain unchanged, you only need to click the "back" button, then, click "forward", and its original resources will still be accessible. However, you can press the "_" key to clear their authentication information.

In addition, before PHP 4.3.3, due to Microsoft IIS restrictions, HTTP authentication cannot work in the CGI mode of the IIS server. To enable PHP 4.3.3 and later versions to work, you need to edit IIS settings "directory security ". Click "edit" and select "anonymous access" only. All other check boxes should be left blank.

Another restriction is that when PHP 4 is used in iis isapi mode, the PHP_AUTH _ * variable cannot be used, but only HTTP_AUTHORIZATION can be used. For example, consider the following code: list ($ user, $ pw) = explode (':', base64_decode (substr ($ _ SERVER ['http _ authorization'], 6 )));.

Note: IIS considerations
To enable HTTP authentication in IIS, set cgi. rfc2616_headers to 0 (default ).

Note:

If the security mode is activated, the script UID is added to the realm part of the WWW-Authenticate header.

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.