Table of Contents
PHP based on form password verification and HTTP verification usage examples, form examples
Home Backend Development PHP Tutorial PHP form-based password authentication and HTTP authentication usage examples, form examples_PHP tutorial

PHP form-based password authentication and HTTP authentication usage examples, form examples_PHP tutorial

Jul 13, 2016 am 10:10 AM
php verify

PHP based on form password verification and HTTP verification usage examples, form examples

The example in this article describes the usage of PHP form-based password authentication and HTTP authentication. Share it with everyone for your reference. The specific analysis is as follows:

PHP’s HTTP authentication mechanism only works when PHP is running as an Apache module, so this feature does not apply to the CGI version. In the PHP script of the Apache module, you can use the header() function to send "Authentication Required" information to the client browser, causing it to pop up a username/password input window. When the user enters the username and password, the PHP script containing the URL will add the predefined variables PHP_AUTH_USER, PHP_AUTH_PW and AUTH_TYPE and be called again. These three variables are set to the username, password and authentication type respectively. Predefined variables are stored in the $_SERVER or $HTTP_SERVER_VARS array. Supports "Basic" and "Digest" (since PHP 5.1.0) authentication methods. Interested friends can refer to the header() function related information.

PHP version issue: Autoglobals global variables, including $_SERVER, etc., are valid since PHP 4.1.0, and $HTTP_SERVER_VARS is valid since PHP 3.

The following is an example script to force client authentication on the page.

Example 34-1. Basic HTTP authentication example

Copy code The code is as follows:
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 "

Hello { $_SERVER [ 'PHP_AUTH_USER' ]} .

" ;
echo "

You entered { $_SERVER [ 'PHP_AUTH_PW' ]} as your password.

" ;
}
?>

Example 34-2. Digest HTTP authentication example

This example demonstrates how to implement a simple Digest HTTP authentication script. For more information, please refer to RFC 2617.

Copy code The code is as follows:
$realm = 'Restricted area' ;
//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.*)",s*realm="(?P.*)",s*nonce="(?P.*)", s*uri="(?P.*)",s*response="(?P.*)",s*opaque="(?P.*)",s* qop=(?P.*),s*nc=(?P.*),s*cnonce="(?P.*)"/' , $_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 issues: Please 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", the delimiting character The string must be quoted with double quotes (not single quotes); and in the header line HTTP/1.0 401, there must be exactly one space before the 401.

In the above example, only the values ​​of PHP_AUTH_USER and PHP_AUTH_PW are printed, but in actual application, it may be necessary to check the validity of the user name and password, perhaps query the database tutorial, or retrieve it from the dbm file .

Note that some Internet Explorer browsers have inherent issues. It seems a bit fussy about the order of headers. Currently it appears that sending the WWW-Authenticate header before sending the HTTP/1.0 401 may resolve this issue.

As of PHP 4.3.0, in order to prevent someone from writing a script to obtain the password from a page authenticated with traditional external mechanisms, when external authentication is valid for a specific page and security mode is turned on, the PHP_AUTH variable will not be setting, but regardless, REMOTE_USER can be used to identify externally authenticated users, so the $_SERVER['REMOTE_USER'] variable can be used.

Configuration instructions:PHP uses the AuthType directive to determine whether the external authentication mechanism is valid.

Note, this still does not prevent someone from using an unauthenticated URL to steal passwords from an authenticated URL on the same server.

Netscape Navigator and Internet Explorer browsers will clear the Windows authentication cache of all local browsers for the entire domain when receiving a 401 server return message. This can effectively log out a user and force them to re-enter their username. name and password, some people use this method to "expire" the login status, or as a response behavior of the "logout" button.

Example 34-3. Example of HTTP authentication that forces re-entering username and password

Copy code The code is as follows:
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 "

Welcome: { $_SERVER [ 'PHP_AUTH_USER' ]}
" ;
echo "Old: { $_REQUEST [ 'OldAuth' ]} " ;
echo "

n " ;
echo "n" ;
echo " n " ;
echo "n" ;
echo "

n" ;
}
?>

This behavior is not necessary for the Basic authentication standard of HTTP, so this method cannot be relied on. The test of Lynx browser shows that Lynx will not clear the authentication file when receiving the 401 server return information, so as long as the authentication is The file inspection requirements have not changed. As long as the user clicks the "Back" button and then clicks the "Forward" button, their original resources can still be accessed. However, users can clear their authentication information by pressing the "_" key.

In the following example, we use the two variables $PHP_AUTH_USER and $PHP_AUTH_PW to verify whether the entrant is legal and allow entry. In this example, the username and password pairs allowed to log in are tnc and nature:

Copy code The code is as follows:
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 it is a wrong username/password pair, force re-authentication
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 references, it is unlikely to use the obvious username/password pairs in the code snippet above, but to use a database or encrypted password file to access them.

Verify user identity based on specified verification information:

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

Copy code The code is as follows:
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 "

You have entered this username: $PHP_AUTH_USER

You have entered this password: $PHP_AUTH_PW

The authorization type is: $PHP_AUTH_TYPE

";
}
?>

Description:

isset() function is used to determine whether a variable has been assigned a value, and returns true or false depending on whether the variable value exists.

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

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

Next, let’s learn how to verify the user’s identity based on the specified verification information. The code is as follows:

Copy code The code is as follows:
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 "

You're authorized!

";
}
}
?>

Here, we first check whether the user has entered the user name and password. If not, a corresponding dialog box will pop up asking the user to enter identity information. Then, we grant the authorization by judging whether the information entered by the user matches the designated user account admin/123. User access rights or prompt the user to enter the correct information again. This method is suitable for websites where all users use the same login account.

Another simple password verification

If you write and run your PHP script under Windows 98, or if you install PHP as a CGI program according to the default settings under Linux, you will not be able to use the above PHP program to implement the verification function. For this reason, Wubian provides you with another simple password verification method. Although it is not very practical, it is still good for learning.

Copy code The code is as follows:
if($_POST[Submit]=="Submit"){ //If the user submits data, perform the operation
$password=$_POST[password]; //Get the data entered by the user and save it in the variable password
$cpassword=$_POST[cpassword]; //Get the confirmation data entered by the user and save it in the variable $cpassord
if(emptyempty($password) || emptyempty($cpassword))
{
Die("Password cannot be empty!");
}
elseif ( ((strlen($password) < 5) || (strlen($password) > 15)))
{
Die("Password length is between 5 and 15");
}
//--- Value comparison
elseif ( !(strlen($password) == strlen($cpassword)) )
{
Die("The passwords entered twice do not match! ");
}
elseif( !($password === $cpassword)) //Compare value and data type
{
die("The two passwords do not match! ");
}
else //Loop to output the password, because it is a password, the * sign is output
{
for ($i=0;$i           {
                 echo "*";
        }
}
}
?>



Form Validation-Password Field Validation



Please enter password:

Confirm password:




I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/938851.htmlTechArticlephp form-based password verification and HTTP verification usage examples, form examples This article describes php form-based password verification and HTTP Verify usage. Share it with everyone for your reference. Detailed analysis...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles