Look at the second Exit message on this page, 'Your credentials are invalid'.
For some reason, I can't get this message to display.
The first exit message does display properly, but that message ends up getting shown all the time, rather than the more custom second Exit message.
How can I get this second message to display?
<?php
require_once('connectvars.php');
?>
<?php
//if username and password not entered, show popup
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Databasename"');
//if they click cancel
exit('Must enter credentials to continue. '); //this works just fine
}
//grab the user entered login data
$user_username = $_SERVER['PHP_AUTH_USER'];
$user_password = $_SERVER['PHP_AUTH_PW'];
//look up the username and password in the database
$query= "SELECT user_id, username
FROM table_name
WHERE username = '$user_username'
AND " . "password = SHA('$user_password')";
$data= mysqli_query($dbc, $query);
if (mysqli_num_rows($data) ==1) {
//the login is okay so set the user id and username variables
$row=mysqli_fetch_array($data);
$user_id = $row['user_id'];
$username = $row['username'];
echo 'You are logged in as ' . $username ; //this all works
}
//here is where my problems begin
else {
//credentials were wrong
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Databasename"');
//if they click cancel here, how come the text below isn't showing? Currently it's like the code jumps back up to the first header exit message.
exit('Your credentials are invalid');
}
?>
Your comment and your code do not match.
//if username and password not entered, show popup
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
The code reads if either PHP_AUTH_USER
or PHP_AUTH_PW
is not set then...
Which means when you leave either username or password blank, the condition will be true.
Easy fix, change ||
to &&
Since isset()
will return true
even when the value is blank, just check whether the value is not blank.
if (!$_SERVER['PHP_AUTH_USER'] && !$_SERVER['PHP_AUTH_PW']) {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.