php - Can't get correct exit message to display when authentication fails
Get the solution ↓↓↓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');
}
?>
Answer
Solution:
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 eitherPHP_AUTH_USER
orPHP_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
||&&
Sinceisset()
will returntrue
even when the value is blank, just check whether the value is not blank.
if (!$_SERVER['PHP_AUTH_USER'] ||&& !$_SERVER['PHP_AUTH_PW']) {
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.