Home Backend Development PHP Tutorial PHP form-based password authentication and HTTP authentication usage_PHP tutorial

PHP form-based password authentication and HTTP authentication usage_PHP tutorial

Jul 20, 2016 am 11:09 AM
apache http php and by based on password Way mechanism module usage of form Certification verify

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. See the header() function for more information.

PHP version issue: Autoglobals global variables, including $_SERVER, etc., are valid since PHP 4.1.0, $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

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. Please refer to RFC 2617 for more information.

$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 take extra care when writing HTTP header code careful. To ensure compatibility with all clients, the first letter of the keyword "Basic" must be capitalized "B", the delimiting string must be quoted in double quotes (not single quotes); and in the header line HTTP/1.0 401 , there must be exactly one space before 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 legitimacy of the user name and password. Perhaps perform a database tutorial query, or retrieve from a dbm file.

Note that some Internet Explorer browsers have their own issues. It seems a bit fussy about the order of headers. It currently 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 will not be set. However, 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 that this still does not prevent someone from stealing passwords via an unauthenticated URL from an authenticated URL on the same server.

Both Netscape Navigator and Internet Explorer browsers will clear the Windows authentication cache of all local browsers in 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 and password. Some people use this method to "expire" login status, or as a responsive behavior for a "logout" button.

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

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' ]} < br />" ;
echo "Old: { $_REQUEST [ 'OldAuth' ]} " ;
echo "

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

n" ;
}


It is not required and therefore cannot be relied upon. Testing of the Lynx browser shows that Lynx will not clear the authentication file when receiving the 401 server return information. Therefore, as long as the inspection requirements for the authentication file do not change, as long as the user clicks the "Back" button and then clicks the "Forward" button, Its 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 user name and password pairs allowed to log in are tnc and nature respectively:

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"; $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 user name/password pair in the code snippet above, but to use a database or encryption password file to access them.

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

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

";

}

?> ) function is used to determine whether a variable has been assigned a value. 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 it before any HTML or PHP code that produces the 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 take a look at how to verify the user’s identity based on the specified verification information. 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 to ask the user to enter Identity information. Subsequently, we grant the user access rights or prompt the user to enter the correct information again by determining whether the information entered by the user matches the specified user account admin/123. This method works for sites where all users use the same login account.

6.4 Another simple password verification

If you are writing and running your PHP script under windows98, or if you follow the default settings under Linux, install PHP as a For CGI programs, 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.

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(empty($password ) || empty($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)) //Comparison of value and data type
{
die("The two passwords do not match! ");
}
else //Loop the password because it is a password. Output the * number
{
for ($i=0;$i 🎜>}
?>


Form Validation-Password Field Validation



Please enter password:

Confirm Password:









http://www.bkjia.com/PHPjc/444769.html

www.bkjia.com

http: //www.bkjia.com/PHPjc/444769.htmlTechArticlePHP’s HTTP authentication mechanism is only effective when PHP is running as an Apache module, so this feature does not apply to CGI Version. In the PHP script of the Apache module, you can use the header() function...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How to run the h5 project How to run the h5 project Apr 06, 2025 pm 12:21 PM

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

Describe the purpose and usage of the ... (splat) operator in PHP function arguments and array unpacking. Describe the purpose and usage of the ... (splat) operator in PHP function arguments and array unpacking. Apr 06, 2025 am 12:07 AM

The... (splat) operator in PHP is used to unpack function parameters and arrays, improving code simplicity and efficiency. 1) Function parameter unpacking: Pass the array element as a parameter to the function. 2) Array unpacking: Unpack an array into another array or as a function parameter.

How to export pdf with xml How to export pdf with xml Apr 03, 2025 am 06:45 AM

There are two ways to export XML to PDF: using XSLT and using XML data binding libraries. XSLT: Create an XSLT stylesheet, specify the PDF format to convert XML data using the XSLT processor. XML Data binding library: Import XML Data binding library Create PDF Document object loading XML data export PDF files. Which method is better for PDF files depends on the requirements. XSLT provides flexibility, while the data binding library is simple to implement; for simple conversions, the data binding library is better, and for complex conversions, XSLT is more suitable.

How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) Apr 08, 2025 am 12:03 AM

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

Explain strict types (declare(strict_types=1);) in PHP. Explain strict types (declare(strict_types=1);) in PHP. Apr 07, 2025 am 12:05 AM

Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values ​​to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.

See all articles