PHP网页安全认证实例详解
本章节详细解析PHP网页安全认证的具体实现方法,涵盖从基础原理到代码实践的完整流程。
第一种方案为不依赖外部存储的认证模式,通常适用于简单场景或临时验证需求。
<?php
//unset($_SERVER['PHP_AUTH_USER']);
$strAuthUser= $_SERVER['PHP_AUTH_USER'];
$strAuthPass= $_SERVER['PHP_AUTH_PW'];
if (! ($strAuthUser == "a" && $strAuthPass == "a")) {
header('WWW-Authenticate: Basic realm="wly"');
header('HTTP/1.0 401 Unauthorized');
echo "用户验证!!";
exit;
} else {
echo "验证通过";
header("location:http://www.baidu.com");
//unset($_SERVER['PHP_AUTH_USER']);
}
?>
第二种方案采用数据库作为用户凭证存储后端,支持更复杂的权限管理和用户数据持久化。
<?php
function authenticate_user() {
header('WWW-Authenticate: Basic realm="Secret Stash"');
header("HTTP/1.0 401 Unauthorized");
exit;
}
if (! isset($_SERVER['PHP_AUTH_USER'])) {
authenticate_user();
} else {
mysql_pconnect("localhost","authenticator","secret") or die("Can't connect to database server!");
mysql_select_db("java2s") or die("Can't select authentication database!");
$query = "SELECT username, pswd FROM user WHERE username='$_SERVER[PHP_AUTH_USER]' AND pswd=MD5('$_SERVER[PHP_AUTH_PW]')";
$result = mysql_query($query);
// If nothing was found, reprompt the user for the login information.
if (mysql_num_rows($result) == 0) {
authenticate_user();
}
}
?>
若在阅读过程中遇到任何疑问,欢迎在评论区留言或通过本站社区进行交流讨论。感谢各位读者的支持与关注,希望这些内容能为您提供实质性的帮助。