HTTP Authentication for PHP

Source: Internet
Author: User
Tags http authentication microsoft iis
PHP's HTTP authentication mechanism only works when PHP is running as an Apache module, so this feature is not available for CGI versions. In the Apache module PHP script, you can use the header () function to send the "authentication Required" message to the client browser, which pops up a username/Password Entry window. When the user enters the user name and password, the PHP script containing the URL will be prefixed with the predefined variables PHP_AUTH_USER,PHP_AUTH_PW and auth_type are called again, these three variables are set to the user name, password and authentication type respectively. The predefined variables are saved in the $_server or $http_server_vars array. Support for "Basic" and "Digest" (since PHP 5.1.0) authentication method.

note:php version Issue

Autoglobals global variables, including $_server, are valid from PHP 4.1.0, $HTTP _server_vars effective starting with PHP 3.

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

Example #1 Basic HTTP authentication Paradigm

<?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>";    }? >

In the browser address bar, enter the script in the server location, pop up the following input box:

If you click Cancel, the output:

Text to send if user hits Cancel Button

If you enter a user name and password, click Sign in:

Hello hello.

You are entered world as your password.

Example #2 Digest HTTP Authentication Example

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

<?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 $A 1 = MD5 ($data [' username ']. ':' . $realm. ':' .    $users [$data [' username ']];    $A 2 = MD5 ($_server[' Request_method '). ': '. $data [' URI ']);    $valid _response = MD5 ($A 1. ': '. $data [' nonce ']. ': ' $data [' NC ']. ': '. $data [' cnonce ']. ': '. $data [' Qop ']. ': '. $A 2);    if ($data [' response ']! = $valid _response) die (' wrong credentials! '); OK, valid username & PASSWORd echo ' Your is 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, ' Respo        NSE ' =>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

Take extra care when writing HTTP header code. In order to guarantee compatibility for all clients, the first letter of the keyword "Basic" must be capitalized as "B", and the delimited string must be quoted in double quotation marks (not single quotes), and in the header row http/1.0 401, must have only one space before 401.

In the above example, only the values of Php_auth_user and PHP_AUTH_PW are printed, but in practice, the legality of the user name and password may need to be checked. Perhaps a query for the database may be retrieved from the dbm file.

Note that some Internet Explorer browsers themselves have problems. It seems a bit fastidious about the order of the headers. It seems to be possible to resolve this issue by sending the Www-authenticate header before sending http/1.0 401.

Since PHP 4.3.0, in order to prevent someone from writing a script from the traditional external mechanism authentication on the page to obtain the password, when the external authentication is valid for a specific page, and the security mode is turned on, the Php_auth variable will not be set. However, Remote_user can be used to identify external authentication users, so you can use $_server[' remote_user '] variables.

Note: Configuration instructions

PHP uses the AUTHTYPE directive to determine whether an external authentication mechanism is valid.

Note that this still does not prevent someone from stealing passwords from authenticated URLs on the same server through an unauthenticated URL.

Netscape Navigator and Internet Explorer browsers will empty the Windows authentication cache for the entire domain of all local browsers when they receive 401 of the service-side return information. This effectively unregisters a user and forces them to re-enter their user name and password. Some people use this method to "expire" the login status, or as a response behavior for the logout button.

Example Example of HTTP authentication #3 forcing re-entry of user names and passwords

<?php function Authenticate () {header (' Www-authenticate:basic realm= ' T        EST 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"; }

This behavior is not required for the Basic authentication standard for HTTP, and therefore cannot be relied upon. The test of Lynx browser indicates that Lynx does not empty the authentication file when it receives 401 of the server's return information, so as long as the inspection requirements for the authentication file are not changed, as long as the user clicks the "Back" button and then clicks the "Forward" button, its original resources can still be accessed. However, users can clear their authentication information by pressing the "_" key.

Also note that HTTP authentication does not work in the CGI mode of the IIS server before PHP 4.3.3 due to limitations of Microsoft IIS. In order to be able to work with PHP 4.3.3 or later, you need to edit the IIS settings "directory Security". Click "Edit" and select "Anonymous Access" only, all other check boxes should be left blank.

Another limitation is that when PHP 4 is used in the ISAPI mode of IIS, the php_auth_* variable cannot be used and 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 precautions
To enable HTTP authentication to work under IIS, the PHP configuration option Cgi.rfc2616_headers must be set to 0 (the default value).

Note:

If Safe mode is activated, the UID of the script is added to the realm 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.