Basic authentication is very basic. It is not really designed to allow responses, such as Wrong Username/Wrong Password.
If a login attempt fails it will prompt you for the username/password again and again, (usually the browsers allow 3 attempts before failing)
Once the login fails you get 1 error message. This could be caused by wrong username/password from cancel option.
If you want to show bad username/password messages I suggest you implement your own authentication form (which is not difficult).
It is also not a good idea to show wrong username, and wrong password explicitly as once I guess the correct username, I will be able to tell from your response saying bad password only. Then i can work on cracking your password knowing I have the username correct.
I have altered your code substantially and tried to explain why in the comments
If you are using apache websserver, all of what you have done can also be achieved using a a simple .htaccess and .htpasswd file
Here is a website that can generate those files for you
http://www.htaccesstools.com/htpasswd-generator/
<?php
// pageauth.php
// Asks for a username and a password and checks it.
// lets define username/password first, so it is easier to change later without digging through the code.
$auth_hash_algorithm = "sha256";
$user_hash = '8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918'; // admin
$pass_hash = '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8'; // password
// If i run your code up under E_STRICT then i get a warning
// Notice: Undefined variable: _SESSION in test.php
// We should really start the session before we use it, not in the conditional logic below
session_start();
// Next I get
// Notice: Undefined index: logged_in in test.php
// the first time through we should test the index logged_in exists before referencing it.
// Assuming logged_in could only ever be set to 1, then we could just test to see if logged_in is not set, rather then != 1
// if($_SESSION['logged_in'] != 1){
if(!isset($_SESSION['logged_in'])){
// First time through it prompts me for a user/name password
// if i leave the username/password blank it says Wrong Username!
// $_SERVER['PHP_AUTH_USER'] is now set to blank and i can't even attempt to login again unless i restart the browser
// I am assuming it was not the intention to only allow 1 login attempt?
$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
$pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
if (hash($auth_hash_algorithm, $user) == $user_hash && hash($auth_hash_algorithm, $pass) == $pass_hash) {
$_SESSION['logged_in'] = 1;
} else {
header('WWW-Authenticate: Basic realm="Catalog Administration"');
header('HTTP/1.0 401 Unauthorized');
echo '<h1>Hey! You can\'t be here!</h1>
<p>Try logging in first!</p>';
exit;
}
}
echo "Success You must be logged in";