<html>
<! BasicFileWrite.php                                         >
<! Chapter 11, Oracle Database XE PHP Web Programming         >
<! by Michael McLaughlin                                      >
<!                                                            >
<! This script demonstrates basic HTTP authentication against >
<! a password file, appending an entry to the password file   >
<! and rendering an entry form with a success or failure      >
<! message.                                                   >
<head>
<title>
  Chapter 11 : BasicFileWrite.php
</title>
<style type="text/css">
  div#centered {border:0;height:50%;top:25%;left:25%;width:50%;
                position:absolute;}
</style>
</head>
<body>
<?php
  // Check basic authentication.
  $valid_user = verify_authentication();

  // 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
  {
    // Assign inputs to variables.
    $userid = $_POST['userid'];
    $passwd = $_POST['passwd'];

    // Set error default.
    $e_code = 0;

    // Verify username and password.
    switch(true)
    {
      // Does user name already exist.
      case (verified_user($userid)):
        $e_code = 1;
        break;
      // Is user name starts with a alphabetic characters.
      case (!ereg("([a-zA-Z]+[a-zA-Z0-9]{0,1})",substr($userid,0,1))):
        $e_code = 2;
        break;
      // Is user name is 6-10 alpha-numeric characters leading a letter.
      case (!ereg("([a-zA-Z]+[a-zA-Z0-9]{5,10})",$userid)):
        $e_code = 3;
        break;
      // Is password is 6 to 10 alpha-numeric characters leading a letter.
      case (!ereg("([a-zA-Z0-9]{5,10})",$passwd)):
        $e_code = 4;
        break;
    }

	// Enter only when user doesn't exist.
	if ($e_code == 0)
	{
        // Join user and encrypted password into a colon delimited string.
        $data = implode(":",array($userid,md5($passwd)));

      // Calll the function to append a line to a file.
      write_string("simplepassword.txt",$data);
    }

    // Display next user form.
    form_display($e_code,$userid);
  }

  // Define a Basic Authentication function.
  function verify_authentication()
  {
    // Check for HTTP basic authentication variables.
    if ((isset($_SERVER['PHP_AUTH_USER'])) &&
        (isset($_SERVER['PHP_AUTH_PW'])))
    {
      // 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($username,$password) = explode(":",$credentials);

        // Find a match and exit.
        if (($_SERVER['PHP_AUTH_USER'] == $username) &&
            (md5($_SERVER['PHP_AUTH_PW']) == trim($password)))
          return true;
      }
    }
  }

  // Make sure user isn't already there.
  function verified_user($userid)
  {
    // 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($username,$password) = explode(":",$credentials);

      // Return there is a user.
      if ($userid == $username)
        return true;
    }

    // Return there is no existing user.
    return false;
  }

  // Define function to write a colon delimited file.
  function write_string($file,$string)
  {
    // Declare a read-only file resource.
    if ($fp = fopen($file,'a+'))
    {
      // Read the two-dimensional array and write or append to a file.
      fwrite($fp,"\n".$string);

      // Close the open file handle.
      fclose($fp);
    }
  }

  // Build entry form.
  function form_display($code,$userid)
  {
    // Designate message by error code.
    switch ($code)
	{
	  case 0:
  	    $message = "You have added user [$userid] successfully.";
	    break;
      case 1:
  	    $message = "User [$userid] is already in use used.";
        break;
      case 2:
        $message = "User [$userid] must start with a character.";
        break;
      case 3:
        $message = "User [$userid] must be between 6 and 10 haracters.";
        break;
      case 4:
        $message = "The password must be between 6 and 10 characters.";
    }

    // Build dynamic form.
    $out  = '<div id=centered>';
    $out .= '<form method="post" action="BasicFileWrite.php">';
    $out .= '<table border="4" bordercolor="silver" cellspacing="0">';
    $out .= '<tr><td align="center" width="400">';
    $out .= '<font size=+3>New User</font>';
    $out .= '</td></tr>';
    $out .= '<tr><td align="center" bgcolor="white" width="400">';
    $out .= '<font color=blue>'.$message.'</font>';
    $out .= '</td></tr>';
    $out .= '<tr><td>';
    $out .= '<table border="0" cellpadding="5" cellspacing="0">';
    $out .= '<tr>';
    $out .= '<td align="right" width="200">User ID:</td>';
    $out .= '<td width="200"><input name="userid" type="text"></td>';
    $out .= '</tr>';
    $out .= '<tr>';
    $out .= '<td align="right" width="200">User Password:</td>';
    $out .= '<td width="200"><input name="passwd" type="password"></td>';
    $out .= '</tr>';
    $out .= '</table>';
    $out .= '</td></tr>';
    $out .= '<tr><td align="center" colspan="2" width="400">';
    $out .= '<input name="submit" type="submit" value="Add User">';
    $out .= '</td></tr>';
    $out .= '</table>';
    $out .= '</form>';
    $out .= '</div>';

    // Render the form in a web page.
    print $out;
  }
?>
</body>
</html>