<?php session_start();  

function
sendGetPage () {
  
//too many ' and " in heredoc?
  
$serverNamePhpSelf = $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
  echo <<< endOfGetPage
<html>
<head>
<title>PHP Generic secure session</title>
</head>
<body onload="document.loginForm.username.focus();">
Login with your username and password over a secure SSL connection.<br>
<form name="loginForm" action="https://$serverNamePhpSelf" method="post">
Username:
<input type="text" size="12" maxlength="20"  name="username">
<br>
Password:
<input type="password" size="12" maxlength="30"  name="password">
<br>
<input name="login" value="Login" type="submit">
</form>

endOfGetPage;
}
########################################################

//initial page load.  get username and password
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  
bail("");
}


$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];

//OK. now test that username and password is valid.  
//uses MySQL  database: myapplication  table: authentication with username and password fields

$dbcnx = @mysql_connect("localhost", "wills", "");
if (!
$dbcnx) {
  
bail( "<p>Unable to connect to the database server!.");
}


$db = "myapplication";
if (! @
mysql_select_db($db) ) {
  
bail("<p>Unable to access the ".$db." database!");
}

$select = "SELECT * FROM authentication WHERE username='".$_SESSION['username']."'";
$result = mysql_query($select);
if (!
$result) {
  
bail("<p>Unable to do authentication<br>" . mysql_error());
}
else {
  
$row = mysql_fetch_array($result);    //should only be one row...
  
if (mysql_num_rows($result) == 0)
    
bail("<p>No such username<br>" . mysql_error());
  else if (
$row["password"] != $_SESSION['password'])
    
bail ("<p>Invalid password");
  else
    echo
"Welcome: ".$_SESSION['username'];  //."   password: ".$_SESSION['password'];
}



function
bail ($reason) {
  
sendGetPage();
  echo
$reason;
  echo
"</body>\n</html>";
  exit();
}

?>