I have a login form that requires a username and a password. I want the top of the form to say "Invalid Password" or "Invalid Username" if the login credentials are wrong. Could someone please offer insight into doing this?
The message says "Invalid Password" if one field is empty right now. I want it to have messages even if there is something in the field if it is wrong.
Here is the Login Form:
<form action="index.php?action=login" method="post">
<fieldset>
<div style="color:red;"><?php echo isset($_REQUEST['err']) && $_REQUEST['err'] == 1 ? "Invalid Password" : "";?></div>
<legend>Login</legend>
<label for="loginName" class="required">Username:</label>
<input id="loginName" name="loginName" type="text"
value="" required />
<label for="password" class="required">Password:</label>
<input id="password" name="password" type="password"
value="" required />
<input id="submit" class="submit" type="submit" value="login"/>
</fieldset>
</form>
This is the login function (it is for a member/admin website so logs into two accounts):
function connect($loginName) {
global $db;
$query = "SELECT email, level, password FROM members WHERE email = '$loginName'";
$result = $db->query($query);
$results = $result->fetch(PDO::FETCH_ASSOC);
return $results;
}
//Login
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/admin/home.php?err=1');
}
if ($loginName === $results['email'] && password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
}
header('Location: /tire/admin/home.php');
}
//Logout
function logout() {
$_SESSION = array();
session_destroy();
}
@bakriawad Here it is where I'm trying your suggestion and it still isn't working. It's telling me $loginName and $password are undefined indexes.
function error_message(){ unset($error);
$loginName = $_SESSION['loginName'];
{$results = connect($loginName);
$loginName === $results['email'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$passwords = password_verify($password,$results['password']);
if(!$results) {$error = "Username not found";} //if no records returned, set error to no username
else //if found {
if ((isset($password)) !== (isset($passwords))) //check password, if matched log him in
{ $error = "Password is wrong"; } //if not matched then set error message
}
}
if(isset($error))echo $error; //if there is an error print it, this can be anywhere in the page
}
$erran array and handle different case based on the error you send through the server side code.err, so I guess that would be what you need to change.