


Two methods to implement user identity authentication in PHP_PHP Tutorial
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
The header is a string sent by the server before sending 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 username 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 can only be used in PHP installed as a module. , $PHP_AUTH_PW, and $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.
Next 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)
)
Explanation:
1. ID is a serial number, which is not zero and is automatically incremented. 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 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 are not authorized to share network resources!";
exit();
}
/*Connect to database*/
$db=mysql_connect("localhost","root","");
//Select database
mysql_select_db ("XinXiKu",$db);
//Query 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, query 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 above Mysql database to store user information.
We first write a user login interface, the file name is login.php, the code is as follows:
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))
{
//Registered user
session_start();
session_register("user");
$user=$myrow["user"];
// Identity verification successful, perform related operations
...
}
else
{
echo" Identity verification failed , you do not have the right to share network resources!";
}
?>
It should be noted here that users can use **http:// in subsequent operations domainname/next.php?user=username** 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 logged 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 the relevant files
Put mod_php4.dll Copy 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 conf/srm. conf file, add a sentence
Include conf/mod_php4.conf
Before doing this, please remove all the setting statements about the CGI mode in your httpd.conf, which is similar to the following part!
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. Test
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Coinbase Security Login Guide: How to Avoid Phishing Sites and Scams? Phishing and scams are becoming increasingly rampant, and it is crucial to securely access the Coinbase official login portal. This article provides practical guides to help users securely find and use the latest official login portal of Coinbase to protect the security of digital assets. We will cover how to identify phishing sites, and how to log in securely through official websites, mobile apps or trusted third-party platforms, and provide suggestions for enhancing account security, such as using a strong password and enabling two-factor verification. To avoid asset losses due to incorrect login, be sure to read this article carefully!

As the world's leading digital asset trading platform, Ouyi OKX attracts many investors with its rich trading products, strong security guarantees and convenient user experience. However, the risks of network security are becoming increasingly severe, and how to safely register the official Ouyi OKX account is crucial. This article will provide the latest registration portal for Ouyi OKX official website, and explain in detail the steps and precautions for safe registration, including how to identify the official website, set a strong password, enable two-factor verification, etc., to help you start your digital asset investment journey safely and conveniently. Please note that there are risks in digital asset investment, please make cautious decisions.

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

This article provides a safe and reliable Binance Exchange App download guide to help users solve the problem of downloading Binance App in the country. Due to restrictions on domestic application stores, the article recommends priority to downloading APK installation packages from Binance official website, and introduces three methods: official website download, third-party application store download, and friends sharing. At the same time, it emphasizes security precautions during the download process, such as verifying the official website address, checking application permissions, scanning with security software, etc. In addition, the article also reminds users to understand local laws and regulations, pay attention to network security, protect personal information, beware of fraud, rational investment, and secure transactions. At the end of the article, the article once again emphasized that downloading and using Binance App must comply with local laws and regulations, and at your own risk, and does not constitute any investment advice.

This article provides safe and reliable guides to help users access the latest official website of BitMEX exchange and improve transaction security. Due to regulatory and cybersecurity threats, it is crucial to identify the official BitMEX website and avoid phishing websites stealing account information and funds. The article introduces the search for official website portals through trusted cryptocurrency platforms, official social media, news media, and subscribes to official emails. It emphasizes the importance of checking domain names, using HTTPS connections, checking security certificates, and enabling two-factor verification and changing passwords regularly. Remember, cryptocurrency trading is high risk, please invest with caution.

LOOM Coin, a once-highly-known blockchain game and social application development platform token, its ICO was held on April 25, 2018, with an issue price of approximately US$0.076 per coin. This article will conduct in-depth discussion on the issuance time, price and important precautions of LOOM coins, including market volatility risks and project development prospects. Investors should be cautious and do not follow the trend blindly. It is recommended to refer to the official website of Loom Network, blockchain browser and cryptocurrency information platform to obtain the latest information and conduct sufficient risk assessment. The information in this article is for reference only and does not constitute investment advice. Learn about LOOM coins, start here!

The Coinbase exchange web version is popular for its convenience, but secure access is crucial. This article aims to guide users to log in to the official Coinbase web version safely and avoid phishing websites and hackers. We will explain in detail how to verify the official portal through search engines, trusted third-party platforms and official social media, and emphasize security measures such as checking the address bar security lock, enabling two-factor verification, avoiding public Wi-Fi, changing passwords regularly, and being alert to phishing emails to ensure the security of your digital assets. Correct access to the official Coinbase website is the first step to protecting your digital currency. This article will help you start your digital currency trading journey safely.

Gate.io Sesame Open Exchange App Download Guide: This article explains the official Gate.io Exchange App Download Method to help you trade cryptocurrency anytime, anywhere. Gate.io App has the advantages of convenience, good user experience, comprehensive functions (spot, contract, leverage, financial management, etc.) and strong security, and provides real-time market information. To ensure safety, be sure to download the App from the official website of Gate.io to avoid downloading malware. The article introduces the official website download steps and iOS and Android installation procedures in detail, and provides frequently asked questions and security suggestions to help you quickly get started with the Gate.io App and start a safe and convenient cryptocurrency trading journey.
