PHP HTTP Authentication

You could easily make this authentication more dynamic by checking a database for the username and password. We can get whatever the user typed into the dropdown box by specifying the following superglobals.

//Username:

<?php echo $_SERVER['PHP_AUTH_USER'];?>

//Password:

<?php echo $_SERVER['PHP_AUTH_PW'];?>

The Code

<?php

$config['admin_username'] = "demo";

$config['admin_password'] = "demo";

if (!($_SERVER['PHP_AUTH_USER'] == $config['admin_username'] &&$_SERVER['PHP_AUTH_PW'] == $config['admin_password'])) {

header("WWW-Authenticate: Basic realm=\"Papermashup.com Demo Admin\"");

header("HTTP/1.0 401 Unauthorized");

echo 'This is what happens if you press cancel';

exit;

}

// if the username and password match show the rest of the content

?>

Be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all browsers, the keyword “Basic” should be written with an uppercase “B”, the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line.

http://papermashup.com/php-http-authentication/

Leave a comment