search
HomeBackend DevelopmentPHP TutorialPHP新手上路(七)_php基础

建设一个简单交互的网站(三)

6. 密码验证

  也许你想在自己的网站放上你的照片集,而且只想给自己知心的朋友看,这时你需要一个密码验证的程序。

6.1 基于HTTP验证

  如何用PHP来实现密码验证的功能呢?我们可以使用简短的PHP代码,使用函数header()发送HTTP标头强制验证,客户端浏览器则弹出供输入用户名和密码的对话框。在PHP中,客户端用户输入的信息传送到服务端之后自动保存在$PHP_AUTH_USER, $PHP_AUTH_PW, 以及 $PHP_AUTH_TYPE这三个全局变量中。利用这些变量,我们就可以根据实现保存在数据文件或数据库中的用户帐号信息验证用户身份。

  不过在这里需要提醒使用者注意的一点是:只有在Apache模块方式运行的时候,PHP脚本才能使用$PHP_AUTH_USER, $PHP_AUTH_PW, 以及 $PHP_AUTH_TYPE这三个变量。如果用户使用的是CGI模式的PHP则无法实现基于HTTP的验证功能。  

6.2 下面,我们就来详细介绍一下如何使用PHP对用户身份进行验证。

  在下例中,我们是使用$PHP_AUTH_USER和$PHP_AUTH_PW这两个变量来验证进入者是否合法并允许进入。在本例中被允许登录的用户名称和密码对分别为tnc和nature:

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") )
{
// 如果是错误的用户名称/密码对,强制再验证
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!";
}
?>

  事实上再实际引用中不大可能如上面使用代码段明显的用户名称/密码对,而是利用数据库或者加密的密码文件存取它们。  

6.3 根据指定的验证信息核实用户身份

  首先,我们可以使用以下代码确定用户是否已经输入了用户名和密码,并显示出用户输入的信息。


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

";

}

?>

说明:
isset()函数用于确定某个变量是否已被赋值。根据变量值是否存在,返回true或false。
header()函数用于发送特定的HTTP标头。注意,使用header()函数时,一定要在任何产生实际输出的HTML或PHP代码前面调用该函数。

  虽然上述代码相当简单,没有根据任何实际值对用户输入的用户名和密码进行有效验证,但是至少我们了解了如何使用PHP在客户端产生输入对话框。

  下面,我们就来了解一下如何根据指定的验证信息核实用户身份。代码如下:


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!

";

}

}

?>

  在这里,我们首先检查用户是否已经输入了用户名称和密码,如果没有则弹出相应对话框要求用户输入身份信息。随后,我们通过判断用户输入的信息是否符合admin/123这一指定用户帐号来授予用户访问权限或提示用户再次输入正确的信息。这种方法适用于所有用户都使用同一登录帐号的网站。  

6.4 另一种简易的密码验证

  如果你是在windows98下面编写和运行着你的PHP脚本,或者是你在Linux下面按默认设置,将PHP安装成一个CGI程序的话,你将无法使用上面的PHP程序来实现验证功能。为此,无边给大家提供了另外一种简易的密码验证的方法。虽然实用性不大,但是拿来学习还是挺好的。
$password = "123";  

// check password
if($pass != $password)
{
echo "管理密码";
echo "
";
echo "请输入你的管理密码:
";
echo "";
echo "";
echo "
";
}
else
{
echo "恭喜你,你已经通过了密码验证";
echo "<script>"; <br>echo 'window.location="http://gophp.heha.net/test/index.php3"'; <br># 通过密码验证后转入的页面 <br>echo "</script>";

}
?>    

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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 Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software