第二次加载页面后,http身份验证在php中无效

时间:2014-11-09 12:03:39

标签: php http-authentication

我两天前在php中了解了这种身份验证,并在练习网站上应用

<?php
require_once('serverconnect.php');

if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Basic realm="Mismatch"');
    exit('<center><h1>Sorry, you must be logged in to access this website</h1></center>');
}
$dbc = connect();
$username = mysqli_real_escape_string($dbc, trim($_SERVER['PHP_AUTH_USER']));
$password = mysqli_real_escape_string($dbc, trim($_SERVER['PHP_AUTH_PW']));

$query = "select user_id, username from mismatch_user where username='$username' and pass=SHA1('$password')";
$result = mysqli_query($dbc, $query) or die('Error in querying the database');
if(mysqli_num_rows($result) == 1) {
    $row = mysqli_fetch_array($result);
    $username = $row['username'];
    $password = $row['pass'];
}
else {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Auhtenticate: Basic realms="Mismatch"');
    exit('<center><h1>Sorry, you must be logged in to access this website</h1></center>');
}

echo '<p> You are looged in as'.$username.'</p>';
?>

首次加载此页面时可以正常工作但是在用户名和密码字段中输入任何错误值后,单击取消按钮并进一步加载页面不会带回该验证窗口。 可能会有缓存问题,请建议我除了通过浏览器保存密码外,我应该怎样做才能让页面每次加载时都要求验证

0 个答案:

没有答案