Php form-based password verification and HTTP verification usage

Source: Internet
Author: User
Tags http authentication php form

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.

PHP version: global variables of Autoglobals, including $ _ SERVER, are valid for PHP 4.1.0 and $ HTTP_SERVER_VARS is valid for PHP 3.

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

Example 34-1. Basic HTTP Authentication

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


Example 34-2. Digest HTTP Authentication example

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

<? Php
$ Realm = 'restricted region ';

// User => password
$ Users = array ('admin' => 'mypass', 'Guest '=> 'guest ');


If (! Isset ($ _ 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 ');
}

// Analize the PHP_AUTH_DIGEST variable
Preg_match ('/username = "(? P <username>. *) ", s * realm = "(? P <realm>. *) ", s * nonce = "(? P <nonce>. *) ", s * uri = "(? P <uri>. *) ", s * response = "(? P <response>. *) ", s * opaque = "(? P <opaque>. *) ", s * qop = (? P <qop>. *), s * nc = (? P <nc>. *), s * cnonce = "(? P <cnonce>. *) "/', $ _ SERVER ['php _ AUTH_DIGEST'], $ digest );

If (! Isset ($ users [$ digest ['username'])
Die ('username not valid! ');


// Generate the valid response
$ A1 = md5 ($ digest ['username']. ':'. $ realm. ':'. $ users [$ digest ['username']);
$ A2 = md5 ($ _ SERVER ['request _ method']. ':'. $ digest ['uri ']);
$ Valid_response = md5 ($ A1. ':'. $ digest ['nonce ']. ':'. $ digest ['nc ']. ':'. $ digest ['cnonce ']. ':'. $ digest ['qop ']. ':'. $ A2 );

If ($ digest ['response']! = $ Valid_response)
Die ('wrong Credentials! ');

// OK, valid username & password
Echo 'your are logged in as: '. $ digest ['username'];

?>


 


Compatibility: 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. You may query the database tutorial or 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.

Configuration Description: 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 34-3. Example of HTTP authentication that forces a new user name and password

<? 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 resourcen ";
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 ['oldau']}";
Echo "<form action = '{$ _ SERVER ['php _ SELF']} 'METHOD = 'post'> n ";
Echo "<input type = 'siden' name = 'seenbefore' value = '1'/> n ";
Echo "<input type = 'den den 'name = 'oldauth' value = '{$ _ SERVER ['php _ AUTH_USER']} '/> n ";
Echo "<input type = 'submit 'value ='re Authenticate'/> n ";
Echo "</form> </p> 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 "_" to clear their authentication information.
 

In the following example, the variables $ PHP_AUTH_USER and $ PHP_AUTH_PW are used to verify whether the entrant is valid and allow access. In this example, the user names and password pairs that are allowed to log on are tnc and nature:

<?

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 buttonn ";

Exit;

}

Else

{

If (! ($ PHP_AUTH_USER = "tnc" & $ PHP_AUTH_PW = "nature "))

{

// If the user name or password pair is incorrect, force re-verification

Header ("WWW-Authenticate: Basic realm =" My Realm "");

Header ("HTTP/1.0 401 Unauthorized ");

Echo "ERROR: $ PHP_AUTH_USER/$ PHP_AUTH_PW is invalid .";

Exit;

}

Else

{

Echo "Welcome tnc! ";

}

?>

In fact, in actual reference, it is unlikely that the above user name/password pairs are used, but the database or encrypted password files are used to access them.

6.3 verify the user identity based on the specified authentication information

First, we can use the following code to determine whether the user has entered the user name and password, and display the information entered by the user.

<? Php

If (! Isset ($ PHP_AUTH_USER )){

Header ('www-Authenticate: Basic realm = "My Private Stuff "');

Header ('HTTP/1.0 401 unauthorized ');

Echo 'authorization Required .';

Exit;

}

Else {

Echo "<P> You have entered this username: $ PHP_AUTH_USER <br>

You have entered this password: $ PHP_AUTH_PW <br>

The authorization type is: $ PHP_AUTH_TYPE </p> ";

}

?>

Note:

The isset () function is used to determine whether a variable has been assigned a value. Returns true or false based on whether the variable value exists.

The header () function is used to send specific HTTP headers. Note: when using the header () function, you must call this function before any HTML or PHP code that generates the actual output.

Although the above Code is quite simple and does not validate the user name and password entered by the user based on any actual value, at least we understand how to use PHP to generate an input dialog box on the client.

Next, let's take a look at how to verify the user identity based on the specified authentication information. The Code is as follows:

<? Php

If (! Isset ($ PHP_AUTH_USER )){

Header ('www-Authenticate: Basic realm = "My Private Stuff "');

Header ('HTTP/1.0 401 unauthorized ');

Echo 'authorization Required .';

Exit;

}

Else if (isset ($ PHP_AUTH_USER )){

If ($ PHP_AUTH_USER! = "Admin") | ($ PHP_AUTH_PW! = "123 ")){

Header ('www-Authenticate: Basic realm = "My Private Stuff "');

Header ('HTTP/1.0 401 unauthorized ');

Echo 'authorization Required .';

Exit;

} Else {

Echo "<P> You're authorized! </P> ";

}

}

?>

Here, we first check whether the user has entered the user name and password. If not, a dialog box is displayed asking the user to enter the identity information. Then, we determine whether the information entered by the user complies with the specified admin/123 user account to grant the user access permission or prompt the user to enter the correct information again. This method applies to websites where all users use the same Logon account.

6.4 another simple password verification

If you write and run your PHP script under Windows 98, Or you install PHP into a CGI program by default under Linux, you will not be able to use the above PHP program for verification. To this end, we provide you with another simple password verification method. Although it is not practical, it is good to learn it.

<? Php
If ($ _ POST [Submit] = "Submit") {// if the user submits data, perform the operation
$ Password = $ _ POST [password]; // obtain user input data and save it in the variable password
$ Cpassword =$ _ POST [cpassword]; // obtain the validation data entered by the user and save it in the variable $ cpassord
If (empty ($ password) | empty ($ cpassword ))
{
Die ("password cannot be blank! ");
}
Elseif (strlen ($ password) <5) | (strlen ($ password)> 15 )))
{
Die ("the password length is between 5 and 15 ");
}
// --- Value Comparison
Elseif (! (Strlen ($ password) = strlen ($ cpassword )))
{
Die ("the two passwords do not match! ");
}
Elseif (! ($ Password ===$ cpassword) // compare the value and Data Type
{
Die ("two passwords do not match! ");
}
Else // cyclically output the password. Because the password is used, the * number is output.
{
For ($ I = 0; $ I <strlen ($ password); $ I ++)
{
Echo "*";
}
}
}
?>
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Title> form verification-Password Field Verification </title>
</Head>
<Body>
<Form name = "form1" method = "post" action = "<? = $ _ SERVER ['php _ SELF ']?> ">
Enter the password: <input type = "text" name = "password"> <br>
Confirm password: <input type = "password" name = "cpassword"> <br>
<Input type = "submit" name = "Submit" value = "submit">
</Form>
</Body>
</Html>

 


Related Article

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.