3

I have 2 projects 1 is just for checking username and password if they exist in the database,which has the function password_verify() working , and the other u can sign up and then log in, but in this 1 the function password_verify is always returning false even thought i have the same code written in both but changed the table name i will post the project, so if anyone can help me please. I did check that it is connecting to the database normally and returning the email result correct but when it comes to comparing hashed pass with the one entered it's always false.

Index.php is the main page and contains only two php lines:

  1. include("signup.php");
  2. include("login.php");

Connection.php

   <?php
$server="localhost";
$db_username="myusername";
$db_password="mypassword";
$db="test_db";

$conn=mysqli_connect($server,$db_username,$db_password,$db);


if(!$conn)
    die ("Connection Failed: ".mysqli_connect_error());


?>

signup.php

<?php
session_start();
if(isset($_POST['signup']))
{   
     function validateFormData($formData)
    {
        $formData=trim(stripcslashes(htmlspecialchars($formData)));
        return $formData;
    }

    $email=validateFormData($_POST['email']);
    $password=validateFormData($_POST['password']);

    if(!$_POST['email'])
        $error.="Please enter an email<br>";

    else if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
    {
        $error.="Please enter a valid email<br>";
    }

    if(!$_POST['password'])
        $error.="Please enter a password<br>";

    else
    {
        if(strlen($_POST['password'])<8)
            $error.="Password must contain at least 8 characters<br>";

        if(!preg_match('`[A-Z]`',$_POST['password']))
            $error.="Password must contain at least one capital letter<br>";
    }

    if($error)
    {
        echo "<div class='alert alert-danger text-center lead'><a class='close red' data-dismiss='alert'>&times;</a>".$error."</div>";
    }
    else
    { 
        include('connection.php');

        $query="SELECT * FROM `diary` WHERE email='".mysqli_real_escape_string($conn,$email)."'";

        $result=mysqli_query($conn,$query);
        $results=mysqli_num_rows($result);

        if($results)
            echo "<div class='alert alert-danger text-center lead'>This email already exists, do you want to log in?<a class='close red' data-dismiss='alert'>&times;</a></div>";

        else
        {
         $selectUser=mysqli_real_escape_string($conn,$email);
         $hashedPass=password_hash($password,PASSWORD_DEFAULT);
         $query="INSERT INTO `diary`(`email`, `password`) VALUES ('$selectUser','$hashedPass')";   
         mysqli_query($conn,$query);
         echo "<div class='alert alert-success text-center lead'>You've been signed up!<a class='close green' data-dismiss='alert'>&times;</a></div>";

         $_SESSION['id']=mysqli_insert_id($conn);


        }
 }

}


?>

login.php

<?php

if(isset($_POST['login']))
{


    function validateFormData($formData)
    {
        $formData=trim(stripcslashes(htmlspecialchars($formData)));
        return $formData;
    }


    $formEmail=validateFormData($_POST['loginEmail']);
    $formPass=validateFormData($_POST['loginPassword']);
    $newPass=password_hash($formPass,PASSWORD_DEFAULT);
    echo $newPass;

    include("connection.php");

    $query="Select * from diary where email='$formEmail' ";

    $result=mysqli_query($conn,$query);

      if(mysqli_num_rows($result)>0)
    {
        while($row=mysqli_fetch_assoc($result))
        { 
            $LogEmail= $row['email'];
            $LogPass= $row['password'];
            echo "<br>".$LogPass;

        }
        if(password_verify($newPass,$LogPass))
        {
            echo "<br>Correct Password";    
        }
          else
              echo "<br>Not Correct"; 
    }


}

?>

output of $newPass is :"$2y$10$dw0AtEExMc41p4nUB3W9kOOWTcNZmQev9jM4emNn7oQNODfu6Ld.q"

output of $LogPass is : "$2y$10$biz6Z5nxsMZXNf7p3ebqw.pksPb1VhWEmoan776rMqOC7VcFRQbrK"

Index

<?php

include("signup.php");
include("login.php");

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Secret Diary</title>

    <link rel="stylesheet" href="css/Normalize.css">
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

    <!--[if IE]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>
    <div class="container">
      <form class="form-horizontal emailForm" role="form" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
          <legend><h1 class="text-center">Sign Up</h1></legend>
        <div class="form-group">
          <label class="control-label col-sm-2" for="email" >Email:</label>
          <div class="col-sm-10">
             <input type="email" class="form-control" style="width:90%" id="email" placeholder="Enter Email"  name="email" value="<?php echo addslashes($_POST['email']);?>">   
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="pwd">Password:</label>
          <div class="col-sm-10">
            <input type="password" class="form-control" style="width:90%" id="pwd" placeholder="Password" name="password">
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-success " id="btnClick" name="signup">Sign Up</button>
          </div>
        </div>
      </form><!--SIGN UP-->

         <form class="form-horizontal emailForm" role="form" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
          <legend><h1 class="text-center">Log In</h1></legend>
        <div class="form-group">
          <label class="control-label col-sm-2" for="LogInEmail" >Email:</label>
          <div class="col-sm-10">
             <input type="email" class="form-control" style="width:90%" id="LogInEmail" placeholder="Enter Email"  name="loginEmail" value="<?php echo addslashes($_POST['loginEmail']);?>">   
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="LogInPassword">Password:</label>
          <div class="col-sm-10">
            <input type="password" class="form-control" style="width:90%" id="LogInPassword" placeholder="Password" name="loginPassword">
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-success " id="btnClick" name="login">Log In</button>
          </div>
        </div>
      </form><!--LOG IN-->
</div>
    <script src="js/JQuery.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    <script src="js/script.js" type="text/javascript"></script>
</body>
</html>
2
  • When the user signs up the password is hashed and stored in the database , and when he wants to log in i take the pass from the <input> and compare it with the hashed one from the database using password_verify, but it's always returning false, and yes it gives the hash value of $formPass Commented Aug 1, 2016 at 1:05
  • yeah i deleted all records and started again just added two records Commented Aug 1, 2016 at 1:34

2 Answers 2

4

You overwrite your $password when you include your dbconnection.

include('connection.php');

has:

$password="mypassword";

Previously you set:

$password=validateFormData($_POST['password']);

so your hashed password is not the user's password, but your DB password.

I would prefix all DB credentials variables with db_. So your database password variable would then be $db_password. This will allow you to have distinct variables throughout your project (I'd think).

Additionally you should be using $formPass, not $newpass. The $newpass is going to be double hashed at the verify function.

$formEmail=validateFormData($_POST['loginEmail']);
$formPass=validateFormData($_POST['loginPassword']);
$newPass=password_hash($formPass,PASSWORD_DEFAULT);

so change:

if(password_verify($newPass,$LogPass))

to:

if(password_verify($formPass, $LogPass))
Sign up to request clarification or add additional context in comments.

Comments

0

password_verify expects the cleartext password as its first argument. To fix your code, remove this line:

$newPass=password_hash($formPass,PASSWORD_DEFAULT);

And change this line:

if(password_verify($newPass,$LogPass))

To the following:

if(password_verify($formPass,$LogPass))

1 Comment

Hey @chris85 Guess I arrived while the question was in flux. No one had written an answer when I posted this and most of the comments discussion was hidden. I just saw the problem in login.php and wrote about it. didn't even realize until just now (upon reading your answer) that there were other issues that had been fixed before my arrival (such as the db password overwrite)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.