0

I've written the following php code to perform basic authentication. I would like to know how I can display text when the user clicks the ok button, and has entered in either an incorrect username or password. I've commented the line that I thought would make it work, but didn't.

$user = array('Bob' => 'bob');
$pass = array('Bob' => 'pass');
$userSuccess = false;
$passSuccess = false;

if(!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']))
{
    header('http/1.1 401 Unauthorized');
    header('www-authenticate: basic');
    echo "<h2> HTTP Error 401: Unauthorized Access </h2>";
    exit;
}
else
{
    foreach($user as $value)
        if($_SERVER['PHP_AUTH_USER'] == $value)
            $userSuccess = true;
    foreach($pass as $value)
        if($_SERVER['PHP_AUTH_PW'] == $value)
            $passSuccess = true;

    if(!$userSuccess || !$passSuccess)
    {
        header('http/1.1 401 Unauthorized');
        header('www-authenticate: basic');
        echo "incorrect stuff";    // I don't get why this line doesn't make it work.
        exit;
    }
}

Thanks for you time.

Jean-Luc
  • 3,563
  • 8
  • 40
  • 78
  • Does it display anything? Do you get any error messages? – Paul Dessert Feb 24 '12 at 01:12
  • Why do you think it does not work? It works. Input anything as a password and/or login three times and you will get your `incorrect stuff` – Cheery Feb 24 '12 at 02:23
  • Not for me... I have to enter the wrong thing in (at least once) and then press escape or click cancel for it to display "incorrect stuff". – Jean-Luc Feb 24 '12 at 03:10

1 Answers1

1

You need to customize the 401 page. How you do this depends on your server.

For example, if using Apache, and assuming it's configured to allow it, you can make a .htaccess file with ErrorDocument 401 /errors/401.html.

Make /errors/401.html however you want, and that's what should be displayed when a 401 error is thrown.

If using nginx, see Nginx - Customizing 404 page, except you obviously want to customize 401 instead of 404.

Community
  • 1
  • 1
simshaun
  • 21,263
  • 1
  • 57
  • 73
  • Thanks for your suggestion. That works. Do you know why my code above didn't work? And perhaps why another person says it works for them? – Jean-Luc Feb 24 '12 at 07:38