Authentication

Using the $_SERVER superglobals array PHP_AUTH_USER and PHP_AUTH_PW values and the header() function to provide a Username/Password popup window.

 

The header() function sends a header request to the browser, requesting an authentication dialog on the client's browser.

 

Upon submission of the credentials, the URL containing the PHP script will be called again with the predefined variables from the $_SERVER array:

  • PHP_AUTH_USER
  • PHP_AUTH_PW
  • AUTH_TYPE

 

<?php
    /* this could be included from a separate credentials.php file or read in from a database */
    $username = "tarquin";
    $password = "secret";

    // check if a username and password have been entered
    if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {    
        header('WWW-Authenticate: Basic realm="Test site"'); //note the use of double quotes inside the single quotes
        header("HTTP/1.0 401 Unauthorized");
        echo ("You must enter a username and password combination");
        exit;
    }
    // check if username and password match values
    elseif (strcmp($_SERVER['PHP_AUTH_USER'],$username) !==0 || strcmp($_SERVER['PHP_AUTH_PW'],$password) !==0) {        
        header('WWW-Authenticate: Basic realm="Test site"'); //note the use of double quotes inside the single quotes
        header("HTTP/1.0 401 Unauthorized");
        echo ("Your username and password was incorrect!");
        exit;
    }
    echo "Hi  $username! you have successfully logged in!";

    // just a quick view of the $_SERVER array to see the entered values
    while (list($key,$value) = each($_SERVER)) {
        print "$key = $value";
    } 
?>

 

Authentication must come before any other HTML output.

Leave a Reply