PHP password_verify()无法成功验证

时间:2015-08-17 12:02:05

标签: javascript php mysql hash

我检查了所有类似的问题和答案,但没有一个对我有用。 我正在使用标准的php散列和验证方法以下是我的代码。

这是用于散列密码的代码

$passwordhash = password_hash($pwd, PASSWORD_DEFAULT);

然后将散列输出存储到mysql数据库表中,该列为varchar数据类型,大小为255.

当使用用户提供的密码检索并验证哈希时,验证将返回false。

验证代码如下所示。

 if($rows2['user_name'] == $username) && password_verify($password ,$rows2['password'])){

  
$_SESSION['login_user']=$username; // Initializing Session

} else {
$error = "Username or Password is invalid";
}

然而,在存储之前使用正确的密码验证哈希提供了真实的答案。

这是存储前验证的代码

if(password_verify($pwd ,$hashpassword )){

 echo "<BR>"." the internal verify before storage"."<BR>";
}

这是存储散列密码的代码。

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "datacentre";

// Create connection
$con = new mysqli($servername, $username, $password, $dbname , 3306);
    

if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}  

 //mysql_select_db("$database", $con);
 $sql= "INSERT INTO admin (user_name , password , time_created)
VALUES ('$u_name' , '$hash' , NOW() )"; 


if ($con->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $con->error;
}

$con->close();

这是检索哈希密码的代码。

if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];


// Create connection
$con = mysqli_connect($db_hostname, $db_username, $db_password, $db_database , 3306);


// Check connection
    if(mysqli_connect_error()){
 die("Connection failed: ".$con->connect_error);
                             }

// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);


// Retrieve data from database

$sql="select * from admin where user_name ='$username'";

$result = mysqli_query($con,$sql);

  while($rows2 = $result->fetch_assoc()){


  if($rows2['user_name'] == $username) && password_verify($password ,$rows2['password'])){

  
$_SESSION['login_user']=$username; // Initializing Session

} else {
$error = "Username or Password is invalid";
}

}

$con->close(); // Closing Connection             

      }

}


}

看起来问题在于数据库如何存储散列密码。 请你需要一个解决方案。

0 个答案:

没有答案