Simple HTTP authentication example

Shows how to use the WWW-Authenticate header to create simple logins.

// Status flag:
$LoginSuccessful = false;
 
// Check username and password:
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
 
    $Username = $_SERVER['PHP_AUTH_USER'];
    $Password = $_SERVER['PHP_AUTH_PW'];
 
    if ($Username == 'jonas' && $Password == 'foobar'){
        $LoginSuccessful = true;
    }
}
 
// Login passed successful?
if (!$LoginSuccessful){
 
    /* 
    ** The user gets here if:
    ** 
    ** 1. The user entered incorrect login data (three times)
    **     --> User will see the error message from below
    **
    ** 2. Or the user requested the page for the first time
    **     --> Then the 401 headers apply and the "login box" will
    **         be shown
    */
 
    // The text inside the realm section will be visible for the 
    // user in the login box
    header('WWW-Authenticate: Basic realm="Secret page"');
    header('HTTP/1.0 401 Unauthorized');
 
    print "Login failed!\n";
 
}
else {
 
    // The user entered the correct login data, put
    // your confidential data in here: 
 
    print 'you reached the secret page!';
}
Snippet Details




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Jonas September 15, 2007 at 12:04
Thank you!

I made a snippet to answer your question, see the related links above.

:-)
william September 14, 2007 at 23:39
first let me say great script. I was wondering is there a way to log out that way if someone else go to the procted page on the same computer they have to login.