PHP Header函数与HTTP认证原理
本示例详解了PHP中借助Header函数配合PHP_AUTH_PW及PHP_AUTH_USER变量进行用户身份验证的实现方式。内容旨在为开发者提供参考与借鉴。
PHP的Header函数具备多种实用功能,其中基于HTTP协议的用户验证便是颇具特色的一项应用。其具体实施步骤如下:
Header("WWW-Authenticate: Basic realm="USER LOGIN"");
Header("HTTP/1.0 401 Unauthorized");
在脚本头部配置相应的Header指令后,页面加载时浏览器将弹出标准登录对话框,提示用户输入账号与密码。相较于传统网页表单登录,这种基于HTTP协议的验证方式显得更为底层且独特。
为接收从上述对话框提交的用户名和密码数据,需调用PHP内置的特殊变量$PHP_AUTH_USER和$PHP_AUTH_PW。需注意,若未在php.ini中启用相关配置,则必须通过以下特定方式引用这些变量:
$_SERVER['PHP_AUTH_USER']
$_SERVER['PHP_AUTH_PW']
成功捕获用户提交的凭证后,后续的业务逻辑处理流程与常规程序无异。以下提供两段参考代码以供学习:
<?php
if(!isset($PHP_AUTH_USER)) {
Header("WWW-authenticate: basic realm="XXX"");
Header("HTTP/1.0 401 Unauthorized");
$title="Login Instructions";
?>
In order to enter this section of the web site, you must be an XXX
subscriber. If you are a subscriber and you are having trouble logging
in,
please contact support@xxx.com.
<?php
exit;
} else {
mysql_pconnect("localhost","nobody","") or die("Unable to connect to SQL server");
mysql_select_db("xxx") or die("Unable to select database");
$user_id=strtolower($PHP_AUTH_USER);
$password=$PHP_AUTH_PW;
$query = mysql_query("select * from users where user_id='$user_id' and password='$password'");
if(!mysql_num_rows($query)) {
Header("WWW-authenticate: basic realm="XXX"");
Header("HTTP/1.0 401 Unauthorized");
$title="Login Instructions";
?>
In order to enter this section of the web site, you must be an XXX
subscriber. If you are a subscriber and you are having trouble
logging in,
please contact support@xxx.com.
<?php
exit;
}
$name=mysql_result($query,0,"name");
$email=mysql_result($query,0,"email");
mysql_free_result($query);
}
?>
另一段参考实现代码如下:
<?php
//assume user is not authenticated
$auth = false;
$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];
if ( isset($user) && isset($pass) )
{
//connect to db
include 'db_connect.php';
//SQL query to find if this entered username/password is in the db
$sql = "SELECT * FROM healthed_workshop_admin WHERE
user = '$PHP_AUTH_USER' AND
pass = '$PHP_AUTH_PW'";
//put the SQL command and SQL instructions into variable
$result = mysql_query($sql) or die('Unable to connect.');
//get number or rows in command; if more than 0, row is found
$num_matches = mysql_num_rows($result);
if ($num_matches !=0)
{
//matching row found authenticates user
$auth = true;
}
}
if (!$auth)
{
header('WWW-Authenticate: Basic realm="Health Ed Presentation Admin"');
header('HTTP/1.0 401 Unauthorized');
echo 'You must enter a valid username & password.';
exit;
}
else
{
echo 'Success!';
}
?>
期望上述内容能对各位的PHP开发工作有所助益。