I have written a code to add users into the database and validate their credentials when a user logs in. Only the added users are allowed to login and for non valid users, simply a username/password does not match error message is echoed. Password encryption and checking codes are not really mine and I extracted them from a tutorial. But my login system "username and password does not match" error message is displayed even for valid users

Here is the code

//Adding Users to the database. When a user is inserted, 
a success message is displayed.
//This code works really fine.
//add.php file
<?php

include_once './connect_database.php';
include_once './functions.php';
session_start();
?>

<!DOCTYPE html>

<?php
function renderForm($username,$password)
{
?>
<html>
    <head>
        <title>Create</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <form action="add.php" method="post">
            Username<input type="text" name="username"><br/>
            Password<input type="password" name="password"><br/>           
            <input type="submit" name="submit" value="Create">
            <?php
            echo $_SESSION["message"];
            $_SESSION["message"]=NULL;
            ?>
        </form>
        <?php
  }
        ?>

        <?php
        $_SESSION["message"];
        //if the form is submitted
        if(isset($_POST['submit'])){

            $username=  cleanData($_POST['username']);
            $password= passwordEncrypt($_POST['password']);

            $query="INSERT INTO admin(username,password) ";
            $query.="VALUES('{$username}','{$password}')";

            $result=confirmQuery($query); 
            echo $result;
            if($result){
                $_SESSION["message"]= 'Record inserted';
                redirectTo("add.php");
            }

            closeDatabase();

        } 
        else
        {
            renderForm("", "");
        }
        ?>
    </body>
</html>


//Validating login. login.php file

<?php

include_once './connect_database.php';
include_once './functions.php';

?>

<!DOCTYPE html>

<?php
 function renderForm($username,$password){
?>
<html>
    <head>
        <title>Login</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <form action="login_results.php" method="post">
            Username<input type="text" name="username"><br/>
            Password<input type="password" name="password"><br/>           
            <input type="submit" name="submit" value="Login">
        </form>
    </body>
</html>
 <?php
} ?>

<?php
 if(!isset($_POST['submit'])){
     renderForm("", "");
 }
?>
//Login form is processed in login_results.php file
<?php
include_once './connect_database.php';
include_once './functions.php';
include_once './login.php';

//if the form is submitted
if(isset($_POST['submit'])){

            $username=  cleanData($_POST['username']);
            $password= passwordEncrypt($_POST['password']);


            $found_user=  loginAttempt($username, $password);
            if($found_user){
               echo 'Welcome '.$found_user['username'];
            }else{
                echo 'Username/pasword does not match';
            }
        } 
        else
        {
            renderForm("", "");
        }
        ?>

      //functions.php includes all my functions

    <?php
function passwordEncrypt($password)
{
    $hashFormat="$2y$10$"; // Tells PHP to use blowfish with a cost of 10
    $saltLength=22 ;//Blowfish salts should be 22 characters or more
    $salt=generateSalt($saltLength); // generate a salt using a function
    $formatAndSalt=$hashFormat.$salt;
    $hashPassword=crypt($password,$formatAndSalt);
    return $hashPassword;
}


function generateSalt($saltLength)
{

    $uniqueRandomString=md5(uniqid(mt_rand(),true));

    //valid characters for a salt are [a-zA-Z0-9./]
    $base64String=base64_encode($uniqueRandomString);

    //But not + which is valid in base64 encoding
    $modifiedBase64String=str_replace('+', '.', $base64String);

    //Truncate string to the correct length 
    $salt=substr($modifiedBase64String,0,$saltLength);
    return $salt;
}

function passwordCheck($password,$existingHash)
{
    $hash=crypt($password,$existingHash);
   if($hash===$existingHash)
   {
    return true;
   }else{
    return false;
}

}


function confirmQuery($query)
{
    global $connection;
    $result=  mysqli_query($connection, $query);
    if(!$result){
       echo "Query failed : ".mysqli_error($connection);
    }
    else
    {
       return $result;
    }
 }

 function redirectTo($newLocation)
 {
    header("Location: ".$newLocation);
    exit;
 }

 function cleanData($escapestr)
 {
   global $connection;
   return mysqli_real_escape_string($connection,$escapestr);
  }

 function closeDatabase()
 {
    global $connection;
    if(isset($connection))
    {
       mysqli_close($connection);
    }
}

function loginAttempt($username,$password)
{
    $queryLogin="SELECT * FROM admin WHERE username='$username' ";

    $userSet=confirmQuery($queryLogin);

    //if username is found, check whether the password is correct
    if($user=  mysqli_fetch_assoc($userSet))
    {

      if(passwordCheck($password, $user["password"]))
      {
           return $user;
      }
      else
      {
            //password does not match
            return false;
      }
    }
    else
    {
        //if no such username is found
        return false;
    }
 }

I have not included connect_databse.php file, that's because I am pretty sure it has no error. I have used that file with other php files without any problem.
Any kind of help will be highly appreciated !!!!! Thanks

Hi,

I suggest you to check following things
a) check that value is enter in database is properly.

Try with different encrypt as md5
For testing purpose use code like
$password= md5($_POST['password']);

and also apply same method in "loginAttempt" function like

Juse Example:

If ( $user["password"] == md5($_POST['password']) ) {
    // Correct
}
else {
    //Invalid
}

Please let me know if you have any more doubt.
Thanks,
Ajay

Dear Ajay
Value is added into the database properly, but user entered password and existing passwords are not similar. I feel like the error is in checkPassword() function, but I have a very similar code which works fine for passwords. In that code I have hardcoded a password.

<?php

function passwordEncrypt($password){
    $hashFormat="$2y$10$"; // Tells PHP to use blowfish with a cost of 10
    $saltLength=22 ;//Blowfish salts should be 22 characters or more
    $salt=generateSalt($saltLength);
    echo $salt; // generate a salt using a function
    $formatAndSalt=$hashFormat.$salt;
    $hashPassword=crypt($password,$formatAndSalt);
    return $hashPassword;

}


function generateSalt($saltLength){

    $uniqueRandomString=md5(uniqid(mt_rand(),true));

    //valid characters for a salt are [a-zA-Z0-9./]
    $base64String=base64_encode($uniqueRandomString);

    //But not + which is valid in base64 encoding
    $modifiedBase64String=str_replace('+', '.', $base64String);

    //Truncate string to the correct length 
    $salt=substr($modifiedBase64String,0,$saltLength);
    return $salt;




}

//This function is used to check whether a given password is equal to existing password

function passwordCheck($password,$existingHash){
$hash=crypt($password,$existingHash);
if($hash===$existingHash){
    echo "Two passwords are equal"."<br/>";
    echo $hash."<br/>".$existingHash;
}else{
    echo "Two passwords do not match"."<br/>";
}


}




?>

<?php
//Testing with dummy data

$password="scret";
$hash= passwordEncrypt($password);


$userInsertedPassword="scret";

passwordCheck($userInsertedPassword,$hash);



?>

Hi!
You can use simple script for login as below.

<?php
session_start();
include_once './connect_database.php';
if(isset($_POST['submit']))
{
    $username = $_POST['username'];
    $password = $_POST['password'];
    $res = mysql_fetch_array(mysql_query("select * from tablename where status='1'"));
    $uname = $res['username'];
    $pword = $res['password'];
    if(($uname==$username)||($pword==$password))
    {
       echo "<div style='color:red'>";
       echo "Invalid Username/Password";
       echo "</div>";
    }
    else
    {
       $query="INSERT INTO admin(username,password) ";
       $query.="VALUES('$username','$password')"; 
       echo "<script>alert('Data added Sucessfully')</script>";
    } 
}
?>

<html>
<head>
<title>Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<form action="login_results.php" method="post">
Username<input type="text" name="username"><br/>
Password<input type="password" name="password"><br/>
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>

These dummy testing seems confusing to me

$password="scret";

$hash= passwordEncrypt($password);

$userInsertedPassword="scret";

passwordCheck($userInsertedPassword,$hash);

if the non-encrypted password is "scret", then why the $userInsertedPassword is also "scret"?

Should it be the inserted password should be equal to the $hash?

try

$password = 'password';
echo passwordEncrypt($password);

Whatever you see on the browser should be the inserted value. For example, if the hash is

 $password = 'password'; // this is from the user input

//$hashed_password = 'asl415sc9rfl'; //this is an assumed output of the passwordEncrypt()

$hashed_password = passwordEncrypt($password);

$saved_password = 'asl415sc9rfl'; // this is from the database

## we validate

    echo(passwordCheck($saved_password,$hashed_password)? 'password is good' : 'password is bad');

For inserting the data into the table use the below code i forget to put mysql_query( ) function inside the else .

$query=mysql_query("INSERT INTO admin(username,password)VALUES('$username','$password')");

use the encrypt() for inserting into the database table and decrypt() for comparing the data

commented: no -3
Member Avatar for iamthwee

Don't be confused with encrypting password and HASHING passwords.

They are completely different. There should be no way for the admin of the site or anyone else for that matter to be able to retrieve the passwords as plain text.

This is the fundamental difference between hashing and encryption.

As far as I can see using crypt() should be just fine. See veedeo's example for further clarification.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.