PHP通过发送头部进行HTTP认证
代码如下:
<?php
header('Content-type: text/html; charset=utf8');
function askAuth ($realm = '请输入认证信息!', $cancelTip = '取消认证!') {
header('WWW-Authenticate: Basic realm="' . $realm . '"');
header('HTTP/1.0 401 Unauthorized');
echo $cancelTip;
exit;
}
$user_info = array(
array('mr.robot', 'wen1234'),
);
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
askAuth();
} else {
foreach ($user_info as $user) {
if ($user[0] == $_SERVER['PHP_AUTH_USER'] && $user[1] == $_SERVER['PHP_AUTH_PW'])
echo '认证通过!';
else {
askAuth('认证失败!');
}
}
}
?>使用Apache服务器的 mod_auth_basic 模块进行HTTP认证
/*****创建 /www/book/.htaccess 文件,访问book目录下面的所有文件都需要认证****/ AuthUserFile D:/.htpasswd AuthType Basic AuthName "Authorization Needed" AuthBasicProvider file Require valid-user ErrorDocument 401 D:/software/phpstudy/PHPTutorial/WWW/knowledge/http-authentication/error.html 注: AuthUserFile 指定了存储用户信息的文件,这个文件使用 "htpasswd -b[c] passwordfile username password" 生成
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号