User Authentication using mysqli_fetch_assoc() function - php

i've been trying to authenticate user input using the mysqli_fetch_assoc function, though it works i.e redirects user to the home page when the username and password is correct, but it doesn't display the error message(s) when the inputs are incorrect however it displays the username error message when the username is incorrect case wise. pls how do i fix it? here is the code
$username = $password = "";
$username_err = $password_err = "";
//testing input values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//processing username input
if (empty($_POST['username'])) {
$username_err = " *username is required!";
}else{ //if field is not empty
$username = test_input($_POST['username']);
}
//processing password input
if (empty($_POST['password'])) {
$password_err = " *password is required!";
}elseif (strlen($_POST['password']) < 8) {
$password_err = " *password must not be less than 8 characters!";
}else{ //if field is not empty
$password = md5($_POST['password']);
}
//comparing user input with stored details
$sql = "SELECT * FROM users_log WHERE Username = '$username' AND Password = '$password'";
$result = mysqli_query($dbconn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row) {
if ($row['Username'] != $username ) {
$username_err = "Incorrect Username";
}elseif ($row['Password'] != $password ) {
$password_err = "Incorrect Password";
}else{
header("location:../home/homeIndex.php");
}
}
}
function test_input($input){
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
the html output
<span><?php echo "$username_err<br>"; ?></span>
<input type="text" name="username" class="form-control" placeholder="Username" size="30">
</div><br>
<?php echo "$password_err<br>"; ?></span>
<input type="password" name="password" class="form-control" placeholder="Password" size="30" >
</div><br>

if ($row) {
if ($row['Username'] != $username ) {
$username_err = "Incorrect Username";
}elseif ($row['Password'] != $password ) {
$password_err = "Incorrect Password";
}else{
header("location:../home/homeIndex.php");
}
}
data inside the $row will execute when condition is true. So use if condition like this,
if ($row) {
header("location:../home/homeIndex.php");
}else{
$username_err = "Incorrect Username Or Password";
}
Hope this will resolve your issue

You are wrapping the incorrect username conditions inside if($row) , this is not going to work as inside query , you are checking for username and password both , but incase any of these is wrong , query is going to return 0 results so that means if($row) is negative and anything inside it will not work ... try below :
if ($row) {
header("location:../home/homeIndex.php");
} else {
$error = "Incorrect Username or password";
}
Why this and $error = "incorrect username or password , it's cause you are not actually checking username and password individually to say , if username is incorrect or password is incorrect. you are checking them both together which makes if($row) not to work as you want , so you better try above one.

If Username or password are incorrect the $result must be empty. Check if !empty($result).

Related

How do I redirect a user to the same URL if the password/email validation fails?

I have a password reset script that has email and password validation. How can I make the script redirect the user to the same URL (ie. "https://www.domain.com/resetpassword.php?token=...") if they fail to meet the validation? Currently, if the validation test fails, the user is redirected to the URL: https://www.domain.com/resetpassword.php. The token is now gone and the password reset page becomes useless.
Here is my PHP code:
<?php
ob_start();
session_start();
include 'connect.php';
// Was the form submitted?
if (isset($_POST['btn-reset']))
{
// Gather the post data
$email = trim($_POST['email']);
$email = strip_tags($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$cpass = trim($_POST['cpass']);
$cpass = strip_tags($cpass);
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have at least 6 characters.";
} else if($pass != $cpass) {
$error = true;
$passError = "Passwords do not match.";
}
// if there's no error, continue to process
if( !$error ) {
$token = $_POST ['token'];
// Retrieve token from database
$stmt = $conn->prepare('SELECT token FROM token WHERE userEmail=? and NOW() < expire_date');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$resetKey = $row['token'];
}
// Does the new reset key match the old one?
if ($resetKey == $token && isset($token))
{
if ($pass == $cpass)
{
//hash and secure the password
$password = password_hash($pass, PASSWORD_DEFAULT);
// Update the user's password
$stmt = $conn->prepare('UPDATE user SET userPass = ? WHERE userEmail = ?');
$stmt->bind_param('ss', $password, $email);
$stmt->execute();
$conn = null;
$sucMSG = "Your password has been successfully reset.";
unset($email);
unset($pass);
unset($cpass);
unset($token);
unset($resetKey);
}
else
$matchError = "Your password's do not match.";
}
else
$keyError = "Your password reset key is invalid.";
}
}
?>
And then I have the errors appear in my form using PHP if the values of the errors are set.

PHP registration form writes data to database even if username/password is short/long or passwords don't match. What to change?

I need help with my PHP registration form. I can't figure out what's wrong. Maybe you can see it. Data sent from my registration form are written to database even if submitted username or password is too short or long and when passwords don't match.
What to change in my code? I've been trying to correct it for hours. Thanks in advance.
Registration form in index.php including <?php session_start(); ?> above HTML
<form class="sign-up" action="users.php" method="post">
<p class="sign-up-title">Username:</p> <input class="sign-up-input" type="text" name="username" min="5" max="25">
<p class="sign-up-title">Password:</p> <input class="sign-up-input" type="password" name="pass" min="6" max="35">
<p class="sign-up-title">Confirm password:</p> <input class="sign-up-input" type="password" name="pass_check" min="6" max="35">
<p class="sign-up-title">E-mail:</p> <input class="sign-up-input" type="email" name="email">
<input id="sign-up-input-submit" class="sign-up-input" type="submit" value="Sign Up">
</form>
<?php
if (isset($_SESSION["username_error_short"])) {
echo $_SESSION["username_error_short"];
}
elseif (isset($_SESSION["username_error_long"])) {
echo $_SESSION["username_error_long"];
}
elseif (isset($_SESSION["username_error_exists"])) {
echo $_SESSION["username_error_exists"];
}
elseif (isset($_SESSION["pass_error_short"])) {
echo $_SESSION["pass_error_short"];
}
elseif (isset($_SESSION["pass_error_long"])) {
echo $_SESSION["pass_error_long"];
}
elseif (isset($_SESSION["pass_error_mismatch"])) {
echo $_SESSION["pass_error_mismatch"];
}
elseif (isset($_SESSION["email_error_exists"])) {
echo $_SESSION["email_error_exists"];
}
elseif (isset($_SESSION["registration_success"])) {
echo $_SESSION["registration_success"];
}
elseif (isset($_SESSION["registration_fail"])) {
echo $_SESSION["registration_fail"];
}
?>
Script in users.php
<?php
session_start();
include "connect.php";
global $db;
if (isset($_POST["username"]) || isset($_POST["pass"]) || isset($_POST["pass_check"])
|| isset($_POST["email"])) {
$username = $_POST["username"];
$password = $_POST["pass"];
$password_check = $_POST["pass_check"];
$email = $_POST["email"];
// check if username is too short/long
if (strlen($username) < 5) {
$_SESSION["username_error_short"] = "Username too short. Username should contain at least 5 characters.";
}
elseif (strlen($username) > 25) {
$_SESSION["username_error_long"] = "Username too long. Username should contain max. 25 characters.";
}
// check if username already exists in DB
elseif (strlen($password) >= 5 || strlen($password) <= 25) {
$sql_User_Duplicate = $db->prepare('SELECT * FROM users WHERE username = :username');
$sql_User_Duplicate->bindParam(':username', $username);
$sql_User_Duplicate->execute();
if ($sql_User_Duplicate->rowCount() > 0) {
$_SESSION["username_error_exists"] = "This username already exists. Select another one.";
}
else {
$usernameCheck = 1;
}
}
// check if password is too short/long
if (strlen($password) < 6) {
$_SESSION["pass_error_short"] = "Password too short. Password should contain at least 6 characters.";
$passwordCheck_length = 0;
}
elseif (strlen($password) > 35) {
$_SESSION["pass_error_long"] = "Password too long. Password should contain max. 35 characters.";
$passwordCheck_length = 0;
}
// check if $password matches $password_check
elseif (strlen($password) >= 6 || strlen($password) <= 35) {
if ($password == $password_check) {
$passwordCheck = 1;
}
else {
$_SESSION["pass_error_mismatch"] = "Passwords don't match. Try again.";
}
}
// check if email already exists in DB
$sql_Email_Duplicate = $db->prepare('SELECT * FROM users WHERE email = :email');
$sql_Email_Duplicate->bindParam(':email', $email);
$sql_Email_Duplicate->execute();
if ($sql_Email_Duplicate->rowCount() > 0) {
$_SESSION["email_error_exists"] = "This e-mail is already registered.";
}
else {
$emailCheck = 1;
}
// create new account
if ($usernameCheck == 1 || $passwordCheck == 1 || $emailCheck == 1) {
$sql_Account_Create = $db->prepare('INSERT INTO users (username, password, email) VALUES (:username, :password, :email)');
$sql_Account_Create->execute(array(":username" => $username, ":password" => $password, ":email" => $email));
// check if account (username) has been created in DB
$sql_Account_Create_Check = $db->prepare('SELECT * FROM users WHERE username = :username');
$sql_Account_Create_Check->bindParam(':username', $username);
$sql_Account_Create_Check->execute();
if ($sql_Account_Create_Check->rowCount() > 0) {
$_SESSION["registration_success"] = "Account registered successfully.";
}
else {
$_SESSION["registration_fail"] = "Something went wrong. Please check submitted data and try again later.";
}
}
}
header('Location: index.php');
?>
These are my recommendations:
Don't limit your users' passwords. I just checked to make sure it's not empty.
It's faster to query SELECT COUNT(*) than SELECT * and count the results.
PDOStatement::execute returns true on success so you don't have to execute another query to see if it inserted correctly
The trailing ?> at the end of the file is unnecessary and actually discouraged in most cases.
Add all of your errors to a single array so that you don't have to test for each type of array in your index.php file. Doing it like that is not only prone to error, it's extremely tedious. You usually want to try to make things as automatic as possible, looping over things instead of trying to remember all of the test conditions you had previously used.
You want to store the hash of the user's password, not the password in plain text. Make sure your password column type is long enough to store bcrypt hashes (see: What column type/length should I use for storing a Bcrypt hashed password in a Database?).
Make sure you unset $_SESSION['errors'] or your users will continue to have the error message displayed to them even after they have successfully filled out the form.
users.php:
<?php
session_start();
include "connect.php";
global $db;
if (isset($_POST["username"]) || isset($_POST["pass"]) || isset($_POST["pass_check"])
|| isset($_POST["email"])) {
$username = $_POST["username"];
$password = $_POST["pass"];
$password_check = $_POST["pass_check"];
$email = $_POST["email"];
// check if username is too short/long
if (strlen($username) < 5) {
$_SESSION["errors"]["username"] = "Username too short. Username should contain at least 5 characters.";
}
elseif (strlen($username) > 25) {
$_SESSION["errors"]["username"] = "Username too long. Username should contain max. 25 characters.";
}
// check if username already exists in DB
elseif (strlen($username) >= 5 || strlen($username) <= 25) {
$sql_User_Duplicate = $db->prepare('SELECT COUNT(*) FROM users WHERE username = :username');
$sql_User_Duplicate->bindParam(':username', $username);
$sql_User_Duplicate->execute();
if ($sql_User_Duplicate->fetchColumn() > 0) {
$_SESSION["errors"]["username"] = "This username already exists. Select another one.";
}
}
// check if password is too short/long
if (empty($password)) {
$_SESSION["errors"]["password"] = "Your password is empty";
}
// check if $password matches $password_check
elseif ($password != $password_check) {
$_SESSION["errors"]["password"] = "Passwords don't match. Try again.";
}
// check if email already exists in DB
$sql_Email_Duplicate = $db->prepare('SELECT COUNT(*) FROM users WHERE email = :email');
$sql_Email_Duplicate->bindParam(':email', $email);
$sql_Email_Duplicate->execute();
if ($sql_Email_Duplicate->fetchColumn() > 0) {
$_SESSION["errors"]["email"] = "This e-mail is already registered.";
}
// create new account
if (!isset($_SESSION['errors']) {
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$sql_Account_Create = $db->prepare('INSERT INTO users (username, password, email) VALUES (:username, :password, :email)');
$inserted = $sql_Account_Create->execute(array(":username" => $username, ":password" => $hash, ":email" => $email));
if ($inserted !== true) {
$_SESSION["errors"]["registration_fail"] = "Something went wrong. Please check submitted data and try again later.";
}
}
}
header('Location: index.php');
And index.php:
<form class="sign-up" action="users.php" method="post">
<p class="sign-up-title">Username:</p> <input class="sign-up-input" type="text" name="username" min="5" max="25">
<p class="sign-up-title">Password:</p> <input class="sign-up-input" type="password" name="pass" min="6" max="35">
<p class="sign-up-title">Confirm password:</p> <input class="sign-up-input" type="password" name="pass_check" min="6" max="35">
<p class="sign-up-title">E-mail:</p> <input class="sign-up-input" type="email" name="email">
<input id="sign-up-input-submit" class="sign-up-input" type="submit" value="Sign Up">
</form>
<?php
if (isset($_SESSION["errors"])) {
?>
There was a problem signing up:
<ul>
<?php
foreach ($_SESSION['errors'] as $err) {
echo "<li>$err</li>";
}
echo '</ul>';
unset($_SESSION['errors']);
}
else {
echo "Account registered successfully.";
}

After hashing the password using md5() and store it into database,cant login again

i built a login and registration system before,is running well.After I hash the input password using md5()and store it to the database,it cant login anymore.So everyone pls look at my code here,so i can know what goes wrong..here is my code here..
signup.php
include ('config.php');
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$username=htmlentities($_POST['username']);
$password=htmlentities($_POST['password']);
$email=htmlentities($_POST['email']);
$cpassword=htmlentities($_POST['cpassword']);
//not empty
//at least 3 characters long
//username and password cannot be same
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields";
}
else if (strlen($username)<6 ) {
$errors['username2'] = "Username should at least 6 characters long";
}
else if (!preg_match('/^[a-z\d_]{3,20}$/i', $username)) {
$errors['username3'] = "Username should contain letters and numbers only.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
else if (strlen($password) <8) {
$errors['password2'] ="Password should at least 8 characters long";
}
else if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,20}$/', $password)){
$errors['password3'] ="Password should contain at least 1 upper-case,1 lower-case,numbers ";
}
//check the password confirmation
if(empty($cpassword)) {
$errors["cpassword2"] = "Must confirm your password to proceed";
}
if($password != $cpassword){
$errors['cpassword1']="Password do not match";
}
//check whether username or password is same
if($username == $password){
$errors['sameuserpass'] ="Username and password cannot be same";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email3'] ="Please enter a vaild email address";
}
//check the errors
if(count($errors) == 0){
$query=mysqli_query($con,"SELECT * FROM user WHERE Username='$username'");
$query1=mysqli_query($con,"SELECT*FROM user WHERE Email='$email'");
if(mysqli_num_rows($query) > 0) {
$errors['userexist'] ="Username already exists";
}
else if(mysqli_num_rows($query1) > 0){
$errors['emailexist'] = "Email already already exists";
}
else {
//HASHING THE PASSWORD
$password = md5($password);
$queryinsert= "INSERT INTO user(Username,Password,Email) VALUES ('$username','$password','$email')";
mysqli_query($con,$queryinsert);
header("Location:login.php");
}
}
}
login.php
<?php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = htmlentities($_POST['email']);
$password = htmlentities(md5($_POST['password']));
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' ");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows !== 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
if($dbemail === $email&&$dbpassword === $password)
{
$_SESSION['email']="$email";
header('Location:user.html');
exit;
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
?>
I successfully store the password that hashed into the database,but the problem is cant login again although the email address and password is correct.Any idea?
signup.php
include ('config.php');
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$email=mysqli_real_escape_string($con,$_POST['email']);
$cpassword=mysqli_real_escape_string($con,$_POST['cpassword']);
//not empty
//at least 3 characters long
//username and password cannot be same
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields";
}
else if (strlen($username)<6 ) {
$errors['username2'] = "Username should at least 6 characters long";
}
else if (!preg_match('/^[a-z\d_]{3,20}$/i', $username)) {
$errors['username3'] = "Username should contain letters and numbers only.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
else if (strlen($password) <8) {
$errors['password2'] ="Password should at least 8 characters long";
}
else if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,20}$/', $password)){
$errors['password3'] ="Password should contain at least 1 upper-case,1 lower-case,numbers ";
}
//check the password confirmation
if(empty($cpassword)) {
$errors["cpassword2"] = "Must confirm your password to proceed";
}
if($password != $cpassword){
$errors['cpassword1']="Password do not match";
}
//check whether username or password is same
if($username == $password){
$errors['sameuserpass'] ="Username and password cannot be same";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email3'] ="Please enter a vaild email address";
}
//check the errors
if(count($errors) == 0){
$query=mysqli_query($con,"SELECT * FROM user WHERE Username='$username'");
$query1=mysqli_query($con,"SELECT*FROM user WHERE Email='$email'");
if(mysqli_num_rows($query) > 0) {
$errors['userexist'] ="Username already exists";
}
else if(mysqli_num_rows($query1) > 0){
$errors['emailexist'] = "Email already already exists";
}
else {
//HASHING THE PASSWORD
$password = md5($password);
$queryinsert= "INSERT INTO user(Username,Password,Email) VALUES ('$username','$password','$email')";
mysqli_query($con,$queryinsert);
header("Location:login.php");
}
}
}
login.php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = mysqli_real_escape_string($con,$_POST['email']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$password = md5($password);
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' ");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows != 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
if($dbemail == $email && $dbpassword == $password)
{
$_SESSION['email']="$email";
header('Location:user.html');
exit;
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
This line?
if($dbemail === $email&&$dbpassword === $password)
Shouldn't it be:
if($dbemail == $email&&$dbpassword == $password)
Edit:
And did you change your original password to a md5 hash or re-register
If you need a hash for your Db password - This -> 2aefc34200a294a3cc7db81b43a81873 will change your password to admins
Edit 2:
And I do recommend that you don't use md5 but this instead.
http://php.net/manual/en/function.password-hash.php

How to compare entered password in input login field with the md5 password stored in database?

UPDATE(solved): Previously I set the password length to 15 characters where it should be 32 character since the password is encrypted to md5. Now it works fine. Thanks for all the answers and suggestions.
Below is the register php code. The code works fine and able to store password in the database in md5.
<html>
<?php
error_reporting(0);
if($_POST['submit'])
{
$name = mysql_real_escape_string($_POST['name']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password1 = mysql_real_escape_string($_POST['password1']);
$enc_password = md5($password);
if($name && $username && $password && $password1)
{
if(strlen($name)<30)
{
if(strlen($username)<10)
{
if(strlen($password)<15 || strlen($password)>6)
{
if($password == $password1)
{
require "dbc.php";
$query = mysql_query("INSERT INTO users VALUES ('$name','$username','$enc_password')");
echo "Registration Complete! <a href='index.php'>Click here to login</a>";
}
else
{
echo "Passwords must match";
}
}
else
{
echo "Your password must be between 6 and 15 characters";
}
}
else
{
echo "Your username is too long";
}
}
else
{
echo "Your name is too long";
}
}
else
{
echo "All fields are required";
}
}
?>
<form action="register.php" method="POST">
Name: <input type="text" name="name" value="<?php echo "$name"; ?>"> Max Length:30<p>
Username: <input type="text" name="username" value="<?php echo "$username"; ?>"> Max Length:10<p>
Password: <input type="password" name="password"> Max length:15<p>
Re-Enter Password: <input type="password" name="password1"><p>
<input type="submit" name="submit" value="Register">
</form>
<input type="button" value="<< Back to Login Area" onclick="window.location='../login%20and%20registration/members.php'">
</html>
Below is the login php code.
<?php
session_start();
require "dbc.php";
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$enc_password = md5($password);
if($username&&$password)
{
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);
if($numrow!=0)
{
while($row = mysql_fetch_assoc($query))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
if($username==$db_username&&$password==$db_password)
{
//echo "Logged in <a href='members.php'>Click here to enter the members area</a>";
$_SESSION['username']=$db_username;
header("location: members.php");
}
else
{
header("location: index.php?error=Incorrect Password");
}
}
else
{
header("location: index.php?error=That user doesn't exist");
}
}
else
{
header("location: index.php?error=All fields are required");
}
?>
The problem is I kept getting the "Incorrect Password" when I try to log in. I think theres something with retrieving the password from the database. Anyone can help?
You need to use $enc_password instead of $password in line:
if($username==$db_username&&$password==$db_password)
P.S. Also if you use md5 then don't do mysql_real_escape_string(), md5 will change your string and all injects will be removed.
P.P.S. Use PDO instead of mysql_*
UPDATE
Also username must be case insensitive so better to do:
if(strcasecmp($username, $db_username)===0 && $password==$db_password)
strcasecmp
change
if($username==$db_username&&$password==$db_password)
to
if($username == $db_username && $enc_password == $db_password)
You are using $password but it should be $enc_password
you're comparing $password with $db_password while you should be comparing $enc_password with $db_password.
if($username==$db_username&&$enc_password==$db_password)
In your case you should compare like this
$password = md5($password);//change value entered of password to md5
if($username==$db_username&&$password==$db_password)

Why errors are not displaying when user logs in incorrectly

I have the following code:
session_start ();
include 'core/init.php';
$username = '';
$password = '';
$dbusername = '';
$dbpassword = '';
if (isset($_POST['Email']) && isset($_POST['Password']))
{
$username = $_POST['Email'];
$password = md5($_POST['Password']);
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
$numrow = mysql_num_rows ($query);
// user login
if ($numrow!=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
$_SESSION ['Email']=$username;
header('Location: member.php?username='.$username);
}
}
else
{
// admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
$numrow2 = mysql_num_rows ($query2);
if ($numrow2!=0)
{
while ($row = mysql_fetch_assoc($query2))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
$_SESSION ['Email']=$username;
header("Location: admin.php");
}else{
if (empty ($username) === true|| empty($password) === true) {
echo "Please enter a username and password";
} else if ($username!=$dbusername){
echo "That user does not exist! Have you registered?";
} else if ($username=$dbusername&&$password!=$dbpassword) {
echo "Incorrect password";
}
}
}
}
}
But if a user logs in incorrectly, none of the error messages are displaying, just a blank page, I think its my curly brackets but no matter how many times i change them i either make it worse or nothing at all. Can anyone tell me what im doing wrong?
Check out:
if (empty ($username) === true|| empty($password) === true) {
echo "Please enter a username and password";
} else if ($username!=$dbusername){
echo "That user does not exist! Have you registered?";
} else if ($username=$dbusername&&$password!=$dbpassword) {
echo "Incorrect password";
}
}
This section which includes login errors is found in the " admin login " section, therefore no error is seen when a non-admin user login fails.
Your select statement is already ensuring that the provided username and password match what is in the database. There is no need to do a second comparison in PHP. Your code could just be the following:
if (isset($_POST['Email']) && isset($_POST['Password']))
{
$username = $_POST['Email'];
$password = md5($_POST['Password']);
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
if(mysql_num_rows($query) == 1)
{
$_SESSION['Email'] = $username;
header('location: member.php?username='.$username);
}
else
{
// try admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
if(mysql_num_rows($query2) == 1)
{
$_SESSION['Email'] = $username;
header("location: admin.php");
}
else
{
echo "Failed Login Attempt";
}
}
}
Since your query only returns records where the username and password match, there is NO way you will ever get a result back where the username matches but the password didn't, so your conditional check you do near the end of your admin login will NEVER occur.
As a side-note, it would be bad form to inform the user that the username was correct but password wasn't, or visa versa. This is a security issue and could make it easier for a malicious user to more easily gain access. This is besides the point though, so please only take this suggestion as personal advice and not directed at your question.
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
if(mysql_num_rows($query) == 0){
echo 'You have entered wrong username/password'; }else {
// you can continue with your query below.

Categories