When users design and maintain sites, they often need to restrict access to certain important files or information. Usually, we can use the user authentication mechanism based on the HTTP protocol built into the WEB server. When a visitor browses a protected page, the client browser will pop up a dialog window asking the user to enter a username and password to verify the user's identity to determine whether the user has the right to access the page. Two methods are used to illustrate its implementation principle.
1. Use HTTP headers to implement
headers. The header is a string sent by the server before transmitting HTML information to the browser using the HTTP protocol. HTTP uses a challenge/response model to authenticate users trying to enter password-protected areas. Specifically, when a user makes a request to the WEB server to access a protected area for the first time, the challenge process is started, and the server returns a special 401 header, indicating that the user's identity has not been verified. After detecting the above response, the client browser automatically pops up a dialog box asking the user to enter a user name and password. After the user completes the input and clicks OK, his or her identification information is sent to the server for verification. If the username and password entered by the user are valid, the WEB server will allow the user to enter the protected area and maintain the validity of their identity throughout the access process. On the contrary, if the user name or password entered by the user cannot be verified, the client browser will continuously pop up an input window asking the user to try to enter the correct information again. The entire process will continue until the user enters the correct information location. You can also set the maximum number of attempts that the user is allowed to make. When exceeded, the user's access request will be automatically denied.
In the PHP script, use the function header() to directly send the HTTP header to the client's browser, so that the username and password input window will automatically pop up on the client to implement our identity authentication function. In PHP, the information entered by the client user is automatically saved in the three global variables $PHP_AUTH_USER, $PHP_AUTH_PW, and $PHP_AUTH_TYPE after it is transmitted to the server. Using these three variables, we can verify the user's identity based on the user account information stored in the data file or database!
However, users need to be reminded that $PHP_AUTH_USER and $PHP_AUTH_PW can only be used in PHP installed as a module. , and the three variables $PHP_AUTH_TYPE. If the user is using PHP in CGI mode, the verification function cannot be implemented. The module installation method of PHP is attached at the end of this section.
Below we use the Mysql database to store the user's identity. We need to extract the username and password of each account from the database to compare with the $PHP_AUTH_USER and $PHP_AUTH_PW variables to determine the authenticity of the user.
First, create a database in MySql to store user information.
The database name is XinXiKu and the table name is user; the table definition is as follows:
create table user(
ID INT(4) NOT NULL AUTO_INCREMENT,
name VARCHAR(8) NOT NULL,
password CHAR(8) NOT NULL,
PRIMARY KEY(ID)
)
Description:
1. ID is a serial number, which is not zero and is automatically incremented. It is the primary key;
2. name is the user name and cannot be empty;
3. password is the user password and cannot be empty;
the following is the user verification file login. php
//Determine whether the username 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);
//Check whether the 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 related operations after successful authentication
...
} else {
//Authentication is unsuccessful, prompt 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 it is not set, it means that authentication is required. The script sends an HTTP 401 error number header to tell the client's browser that authentication is required. The client's browser pops up an authentication window, prompting the user to enter the user name and password. After the input is completed, the connection Database, check whether the username and password are correct. If correct, allow login to perform related operations. If incorrect, continue to require the user to enter username and password.
Function description:
1. isset(): used to determine whether a variable has been assigned a value. Depending on whether the variable value exists, return true or false
2. header(): used to send specific HTTP headers. Note that when using the header() function, be sure to call it before any HTML or PHP code that produces the actual output.
3. mysql_connect(): Open the MySQL server connection.
4. mysql_db_query(): Send the query string (query) to the MySQL database.
5. mysql_fetch_row(): Returns each field of a single column.
2. Use session to implement server verification.
For pages that require authentication, it is best to use apache server verification. However, the interface of apache server verification is not friendly enough. Moreover, PHP in CGI mode and PHP under IIS cannot be verified using the Apache server. In this way, we can use the session to save the user's identity between different pages to achieve identity verification.
On 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, the code is:
____________________________________________________________
<form action="login1.php">
Username:<input type="text" name="name"><br>
Password :<input type="text" name="pass"><br>
<input type="submit" value="Login">
</form>
____________________________________________________________
login1.php processes the submitted form, the code is as follows:
$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)) {
//Register user
session_start();
session_register("user");
$user=$myrow["user"];
// Identity verification successful, perform related operations
...
} else {
echo "Authentication failed, you do not have permission to share network resources!";
}
?>
It should be noted here that users can use **http://domainname/next.php?user=username** in subsequent operations to bypass authentication. Therefore, subsequent operations should first check whether the variable is registered: if it is registered, perform the corresponding operation, otherwise it will be regarded as illegal login. The relevant code is as follows:
session_start();
if (!session_is_registered("user")){
echo "Authentication failed, illegal login!";
} else {
//Successfully log in to perform related operations
...
}
?>
Appendix: How to install PHP in module mode
1. First download the file: mod_php4-4.0.1-pl2. [If yours is not PHP4, then upgrade as soon as possible!]
After unzipping, there are three files: mod_php4.dll, mod_php4.conf, readme.txt
2. Copy related files. Copy
mod_php4.dll to the modules directory of the apache installation directory.
Copy 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 the sentence
Include conf/mod_php4.conf
to do this. Before, please remove all the setting statements about CGI mode in your httpd.conf, that is, the part similar to the following!
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
If you want to make PHP support more suffixes, no problem. The given configuration file mod_php4.conf already supports three suffixes: php, php3, and php4. If you want to support more suffixes, you can change this file. It is very simple.
4.
Use <? phpinfo(); ?> to test. You will see that the value of Server API is apache, not cgi, and there is also information about HTTP Headers Information.