Reputation: 2120
I have a login Form index.php
which has input as ID and Password.I get the input and submit it to another File called
login_user.php
which accepts the data.
If the Credentials are correct then User is routed to the home Page correctly. But when the user has put wrong login details, I have to check with the stored values in the DB.So what I thought is using some variable
in login_user.php
and then include
it in index.php
and print the error in the div
. So far I made this code.
<div class="alert alert-warning alert-dismissible" role="alert" id="alert_login_error">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong id="error_flag">
Invalid Login Details
</strong>
</div>
<?php
include "login_user.php";
if (empty($error)) {
echo "<script> $('#alert_login_error').hide(); console.log('empty');</script>";
}
else {
echo "<script> $('#alert_login_error').show();console.log('not empty');</script>";
}
?>
And login_user.php
file has this
$error = ""; #this is set at the start of the file
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
#User is redirected to Home Page if details are correct
#If the password is wrong then in a function
$error = "Invalid password";
header('Location: index.php');
}
else {
$error = "Invalid Login details";
header('Location: index.php');
}
What this code does
When
index.php
is loaded thediv
in which error is defined is hide. This works fine.but when user inputs wrong login inputs. then also the
div
is set to hide
I don't understand where I am making mistake.If anything more is needed please ask, so that I can provide.Thanks in advance!
Upvotes: 0
Views: 128
Reputation: 622
I personnally use $_SESSION variable to manage errors through PHP script.
Your div would be
<div id='error'> {$_SESSION['error']} </div>
And you kill it just after you displayed it.
This is heredoc syntax. Sorry if you're not used to it.
In this way, you don't have to manage show/hide div, since the div will be empty if $_SESSION['error']
is empty
Note : I don't know if this is a good solution, but it is a working solution at least!
So your PHP script would be :
if ($num_rows > 0) {
#User is redirected to Home Page if details are correct
#If the password is wrong then in a function
$_SESSION['error'] = "Invalid password";
header('Location: index.php');
}
else {
$_SESSION['error'] = "Invalid Login details";
header('Location: index.php');
}
Upvotes: 1
Reputation: 770
You are immediately redirecting the user using your header('location: index.php')
code; as soon as this happens, $error
is wiped clean in the event of a clean page load, which means that your if (empty($error))
conditional will always evaluate to true
.
Upvotes: 2