How to use basic authentication

A login dialog box

login dialog box image

A protected page

protected page image

The unauthorized page

unauthorized page image

The $_SERVER array

Index Description
PHP_AUTH_USER Returns the username from the authentication dialog box or a NULL value if the dialog box hasn’t been displayed.
PHP_AUTH_PW Returns the password from the authentication dialog box or a NULL value if the dialog box hasn’t been displayed.

Code that forces a valid admin user (util/valid_admin.php)

      <?php
require_once('model/database.php');
require_once('model/admin_db.php');

$email = '';
$password = '';    
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $email = $_SERVER['PHP_AUTH_USER'];
    $password = $_SERVER['PHP_AUTH_PW'];    
}

if (!is_valid_admin_login($email, $password)) {
    header('WWW-Authenticate: Basic realm="Admin"');
    header('HTTP/1.0 401 Unauthorized');
    include('unauthorized.php');
    exit();
}
?>
      

Code that’s included at the top of the each protected page

      <?php 
      require_once('util/secure_conn.php'); // require a secure connection
      require_once('util/valid_admin.php'); // require a valid admin user
      ?>      
      

Description

Back