<html>
<! BasicFileLoginRealm.php                                    >
<! Chapter 11, Oracle Database XE PHP Web Programming         >
<! by Michael McLaughlin                                      >
<!                                                            >
<! This script demonstrates basic HTTP authentication.        >
<head>
<title>
  Chapter 11 : BasicFileLoginRealm.php
</title>
<style type="text/css">
  div#centered {border:0;height:50%;top:25%;left:25%;width:50%;
                position:absolute;}
</style>
</head>
<body>
<?php
  // Set initial state for invalid credentials.
  $valid_user = false;

  // Check for HTTP basic authentication variables.
  if ((isset($_SERVER['PHP_AUTH_USER'])) &&
      (isset($_SERVER['PHP_AUTH_PW'])))
  {
    if (!isset($_SERVER['HTTP_AUTHORIZATION']))
	  print "true";

    // Read the file into an array of strings.
    $passwords = file("simplepassword.txt");

    // Read through the value list.
    foreach ($passwords as $credentials)
    {
	  // Break the delimited lines into scalar variables.
      list($userid,$password) = explode(":",$credentials);

	  // Find a match and exit.
      if (($_SERVER['PHP_AUTH_USER'] == $userid) &&
          (md5($_SERVER['PHP_AUTH_PW']) == trim($password)))
      {
	    // Reset invalid credential state variable.
        $valid_user = true;
		break;
      }
    }
  }

  // When credentials are invalid prompt for them.
  if (!$valid_user)
  {
    // Send headers to force basic HTTP authentication.
    header('WWW-Authenticate: Basic Realm="www.techtinker.com"');
	header('HTTP/1.0 401 Unauthorized');

	// Print failed validation message.
    print "<html><body><font size=+2>";
	print "The site has logged your [".$_SERVER['REMOTE_ADDR']."] IP ";
    print "address, please enter a valid user and password.";
	print "</font></body></html>";
    exit;
  }
  else
  {
    // Render the username and password sent.
    print '<div id=centered>';
    print '<table border="1" bordercolor="silver" cellspacing="0">';
    print '<tr>';
    print '<td><b>Variable Name</b>&nbsp;</td>';
    print '<td align="center" width="100"><b>Clear Text</b></td>';
    print '</tr>';
    print '<tr>';
    print '<td align="right" width="150"><b>PHP_AUTH_USER</b></td>';
    print '<td align="center">';
	print $_SERVER['PHP_AUTH_USER'];
    print '</td>';
    print '</tr>';
    print '<tr align="center">';
    print '<td align="right" width="150"><b>PHP_AUTH_PW</b></td>';
    print '<td>';
	print $_SERVER['PHP_AUTH_PW'];
    print '</td>';
    print '</tr>';
    print '</table>';
    print '</div>';
  }
?>
</body>
</html>