Example Learning PHP program for user authentication implementation of two methods _php tutorial

Source: Internet
Author: User

Users often need to restrict access to certain important files or information when they design and maintain a site. In general, we can adopt the HTTP protocol-based user authentication mechanism built into the Web server. When a visitor browses a protected page, the client browser pops up a dialog window asking the user to enter a user name and password to verify the user's identity to determine whether the user has access to the page. The following two methods are used to illustrate the principle of implementation.

First, with the HTTP header to achieve

A header is a string that the server sends HTML messages to the browser before the HTTP protocol. HTTP uses a challenge/response pattern to authenticate users attempting to enter a password-protected zone. Specifically, when a user makes a request to the Web server to access a protected zone for the first time, the challenge process is started and the server returns a special 401 header indicating that the user's identity is unverified. The client browser automatically pops up a dialog box after detecting the above response, requiring the user to enter a user name and password. After the user completes the input and clicks OK, the identification information is transmitted to the server for verification. If the user enters a valid user name and password, the Web server will allow the user to enter the protected area and maintain the validity of its identity throughout the access process. Conversely, if a user enters a user name or password that cannot be verified, the client browser will constantly eject the input window asking the user to try to enter the correct information again. The entire process will persist until the user enters the correct information location, or you can set the maximum number of times a user is allowed to try, and the user's access request will be automatically denied when it is exceeded.

In the PHP script, the function header () is used to send HTTP headers directly to the client's browser, so that the client will automatically pop up the username and Password Input window to implement our identity authentication function. In PHP, the information entered by the client user is automatically saved in the $PHP _auth_user, $PHP _AUTH_PW, and the three global variables $PHP _auth_type. Using these three variables, we can verify the user identity based on the user account information stored in the data file or database.

However, it is important to remind users that $php_auth_user, $PHP _AUTH_PW, and the three variables $PHP _auth_type, are only available in PHP, which is installed in a modular manner. If the user is using CGI mode PHP, the validation function cannot be implemented. The module-mode installation method of PHP is attached to this section.

Below we use the MySQL database to store the user's identity. We need to extract the user name and password for each account from the database to compare the $php_auth_user and $PHP_AUTH_PW variables to determine the authenticity of the user.

First, create a database that holds user information in MySQL

The database name is Xinxiku, the table name is user, and the table is defined as follows:

CREATE TABLE User (
ID INT (4) Not NULL auto_increment,
Name VARCHAR (8) is not NULL,
Password CHAR (8) Not NULL,
PRIMARY KEY (ID)
)

Description

1, ID is a serial number, not zero and automatically increment, the primary key;

2, name is the user name, can not be empty;

3, password for the user password, can not be empty;

The following is a user authentication file login.php

Determine if the user name is set
if (!isset ($PHP _auth_user)) {
Header ("Www-authenticate:basic realm=" Authentication function "");
Header ("http/1.0 401 Unauthorized");
echo "Authentication failed, you do not have permission to share network resources!";
Exit ();
}
/* Connect to Database */
$db =mysql_connect ("localhost", "root", "");
Select Database
mysql_select_db ("Xinxiku", $db);
Querying whether a user exists
$result =mysql_query ("select * from user where name= $PHP _auth_user and password= $PHP _auth_pw", $db);
if ($myrow = Mysql_fetch_row ($result)) {
The following are the relevant actions after successful authentication
...
} else {
Authentication unsuccessful, prompting the user to re-enter
Header ("Www-authenticate:basic realm=" Authentication function "");
Header ("http/1.0 401 Unauthorized");
echo "Authentication failed, you do not have permission to share network resources!";
Exit ();
}
?>

Program Description:

In the program, first check whether the variable $php_auth_user has been set. If there is no setting, the instructions need to be verified, the script issued an HTTP 401 error xwould flag, tells the client browser needs to authenticate, the client's browser pops up an authentication window, prompting the user to enter a user name and password, enter the completion, connect to the database, query the user name and password is correct, If it is correct, allow the login to do so, and if it is not correct, continue to require the user to enter a user name and password.

Function Description:

1, Isset (): Used to determine whether a variable has been assigned a value. Returns TRUE or false depending on whether the value of the variable exists

2. Header (): Used to send a specific HTTP header. Note that when using the header () function, be sure to call the function in front of any HTML or PHP code that produces the actual output.

3, mysql_connect (): Open the MySQL server connection.

4. Mysql_db_query (): Send query string to MySQL database.

5, Mysql_fetch_row (): Returns the fields of a single column.

Second, use the session to implement server authentication

For pages that require authentication, it is best to use Apache server Authentication. However, the Apache server verifies that the interface is not friendly. Furthermore, PHP under the php,iis of CGI mode cannot be verified with Apache server. In this way, we can use the session to save the user identity between different pages, to achieve the purpose of authentication.

In the backend we also use the MySQL database above to store user information.

We first write a user login interface, the file name is login.php, code post:

____________________________________________________________

____________________________________________________________

Login1.php process the submitted form with the following code:

$db =mysql_connect ("localhost", "root", "");
mysql_select_db ("Xinxiku", $db);
$result =mysql_query ("select * from user where name= $name and password= $pass", $db);
if ($myrow = Mysql_fetch_row ($result)) {
Registered users
Session_Start ();
Session_register ("user");
$user = $myrow ["User"];
Authentication successful, related operations
...
} else {
echo "Authentication failed, you do not have permission to share network resources!";
}
?>
It is necessary to note that users can bypass authentication by using **http://domainname/next.php?user= username * * in subsequent operations. Therefore, the subsequent operation should check whether the variable is registered: registered, then the corresponding operation, otherwise considered illegal login. The relevant code is as follows:
Session_Start ();
if (!session_is_registered ("user")) {
echo "Authentication failed, belongs to illegal login!";
} else {
Successful login for related operations
...
}
?>

Appendix: Php Installation method in a modular manner

1, first download files: mod_php4-4.0.1-pl2. [If you are not a PHP4, then upgrade it quickly!]

After unlocking there are three files: Mod_php4.dll, mod_php4.conf, readme.txt

2. Copies of related documents

Copy the Mod_php4.dll to the modules directory of the Apache installation directory

Copy the mod_php4.conf to the Conf directory of the Apache installation directory

Copy the Msvcrt.dll file to the Apache installation directory

3. Open the Conf/srm.conf file and add a sentence

Include conf/mod_php4.conf

Before doing this, please take your httpd.conf in the CGI mode so that the setup statements are removed, that is, similar to the following section!

scripalias/php4/"c:/php4/"
AddType application/x-httpd-php4. php
AddType APPLICATION/X-HTTPD-PHP4. php3
AddType APPLICATION/X-HTTPD-PHP4. PhP4
Action Application/x-httpd-php4/php4/php.exe

To make PHP support more suffix names, no problem. In the given configuration file mod_php4.conf has supported three suffix names PHP,PHP3,PHP4, if you also want to support more suffix name can change this file, very simple.

4. Testing

Use the test. You will see that the server API has a value of Apache, not CGI, and also information about HTTP Headers information.

http://www.bkjia.com/PHPjc/508238.html www.bkjia.com true http://www.bkjia.com/PHPjc/508238.html techarticle users often need to restrict access to certain important files or information when they design and maintain a site. In general, we can adopt the HTTP protocol-based user identity built into the Web server ...

  • 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.