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.

3
  • Does it display anything? Do you get any error messages? Commented Feb 24, 2012 at 1: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 Commented Feb 24, 2012 at 2: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". Commented Feb 24, 2012 at 3:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.