I put together this login script, complete with a section to check for and report errors if the user failed to enter any one of the fields in the login form. The script works perfectly fine when I exclude the error section, but when I include the error section, nothing works. I get redirected to the login failed page (see script) both when I enter the the right username/password combination and when I deliberately mis spell them. I get the same results when I deliberately forget to fill out one of the fields, instead of the appropriate error messages. so who can tell me what I left out or didn’t do right in this script?
<?php
//address error handling
ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);
//Turn on output buffering. Allows for headers to be called anywhere on script. See pg228 Ulman.
ob_start();
if (isset($_POST['submitted'])) {
$errors = array();
// Connect to the database.
require_once ('config.php');
// Initialize a session:
session_start();
//Check for errors.
//Check to make sure they entered their first name.
if (empty($_POST['username'])) {
$errors[] = '<font color="red">Please enter your user name.</font>';
} else {
$username = mysql_real_escape_string($_POST['username']);
}
//Check to make sure they entered their password.
if (empty($_POST['password'])) {
$errors[] = '<font color="red">Please enter your password.</font>';
} else {
$username = mysql_real_escape_string($_POST['password']);
}
//Query the database. The variable assigned to the post username should match the named attribute of username of login form. same for the password.
$sql="SELECT * FROM members WHERE username='$username' AND password='$password' AND activation_status ='1'";
$result=mysql_query($sql);
// Replace counting function based on database you are using.
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1
if($count==1){
// Register username, firstname and redirect to file
session_regenerate_id();
$member = mysql_fetch_assoc($result); //Define a member array that holds result values.
$_SESSION['id'] = $member['member_id'];
$_SESSION['firstname'] = $member['firstname'];
$_SESSION['lastname'] = $member['lastname'];
session_write_close();
header("location: member.php");
exit();
}else {
//Login failed
header("location: login_failed.php");
exit();
}
//Display error messages.
} else {// if errors array is not empty
echo '<h3>Error!</h3>
The following error(s) occured:<br />';
foreach ($errors as $msg) {
echo " - <font color=\"red\">$msg</font><br />\n";
}
}
?>