Week 2 - Secure Login Code
session_start();
$_SESSION['err'] = $err;
if (isset($_POST['userid']) && isset($_POST['password'])) {
// if the user has just tried to log in
include "db/db_connect.php";
// remove all HTML tags, and escape any other special characters
$userid = cleanup_text($_POST['userid']);
$password = cleanup_text($_POST['password']);
//trim white space
$userid = trim($userid);
$password = trim($password);
//check the string length
$userid = string_length($userid, '20');
$password = string_length($password, '40');
// encrypt password
$passwordHash = sha1($password);
$query = 'select * from customers'
." where username='$userid' "
." and password='$passwordHash' "
." limit 1";
$result = safe_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// if they are in the database register the user id
$_SESSION['valid_user'] = $userid;
}
mysql_close($db_conn);
}
if (isset($_SESSION['valid_user'])) {
echo '<h2 style="color:green;">You are logged in as: '.$_SESSION['valid_user'].' </h2>';
echo '<p>You can <a href="logout.php">Log out</a> now.</p>';
}
else
{
if (isset($userid)) {
// if they've tried and failed to log in
echo '<h2 style="color:red;">Sorry, could NOT log you in.</h2>';
$err++;
if($err >= 3) {
echo"<p><strong>Three strikes you're out!</strong></p>";
echo '<p>Please contact the <a href="mailto:jh@uninetnews.com">Account Admin</a></p>';
$direct_to = "jh@uninetnews.com";
$msg ="USER: $userid has failed 3 times to login!\n";
$to = $direct_to;
$subject = "Message from Week 2 Security Log-in Page ";
$mailheaders = "From: Security Alert <> \n";
$mailheaders .= "Reply-To: Do Not Reply\n";
mail($to, $subject, $msg, $mailheaders);
$to == "";
$subject == "";
$msg == "";
$mailheaders == "";
}//end if for errors
}
else
{
// they have not tried to log in yet or have logged out
echo '<h2 style="color:red;">You are not logged in.</h2>';
if($err > 3) {
echo '<p>Please contact the <a href="mailto:jh@uninetnews.com">Account Admin</a></p>';
}//end if err
}
if($err < 3) {
// provide form to log in
echo '<form method="post" action="secureauth.php" name="login" onsubmit="return checkForm()">';
echo '<pre> <label for="userid">Userid: </label>';
echo ' <input type="text" id="userid" name="userid" maxlength="20" /><br /><br />';
echo ' <label for="password">Password: </label>';
echo '<input type="password" id="password" name="password" maxlength="40" /></pre>';
echo ' <input type="submit" value="Log in" />';
echo '</form>';
}//end if err
}