PHP password_verify始终返回false

时间:2015-12-17 16:49:10

标签: php mysql passwords

我一直在开发一个Android应用程序,用于注册并将用户登录到远程MySQL数据库。我已经将我的Android代码以及从应用程序发送到PHP的信息进行了双重检查。

显然,问题出在login.php文件中。用户注册成功,但之后我无法登录。

我的数据库有3个字段:

  • id / int(11)
  • email / varchar(255)
  • 密码/ char(60)

注册用户为密码字段提供了60个字符的哈希值。到现在为止还挺好。但是当我尝试登录时,我总是得到失败的回复。

我正在使用https://github.com/ircmaxell/password_compat,因为我只限于PHP 5.4

这是我的登录PHP代码:

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
    $email = $_POST['email'];
    $passwordFromPost = $_POST['password']; 
    require_once('dbconnect.php');  
    $sql = "SELECT password FROM users WHERE email = '$email'";
    $hash = mysqli_query($con, $sql);
    require_once('lib/password.php');
    if (password_verify($passwordFromPost, $hash)) {
        echo 'success';
    } else {
        echo 'failure';
    }
}
?>

以防万一,这是我注册的PHP代码:

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
    $email = $_POST['email'];
    $passwordFromPost = $_POST['password'];
    require_once('lib/password.php');
    $hash = password_hash($passwordFromPost, PASSWORD_BCRYPT);
    if($hash) {
        require_once('dbconnect.php');
        $sql = "INSERT INTO users (email, password) VALUES ('$email','$hash')";     
        if(mysqli_query($con, $sql)){
            echo "Registered succesfully";
        } else {
            echo "Unable to register the account";
        }
    } else {
        echo 'error';
    }
} else {
    echo 'error';
}
?>

任何帮助将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:2)

你忘了取你的行了。因此,您没有验证字符串。

<?php

$result = mysqli_query($con, $sql);
$row    = mysqli_fetch_array($result);
password_verify($passwordFromPost, $row['password']);

答案 1 :(得分:0)

您的登录php文件应为

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
 $email = $_POST['email'];
 $passwordFromPost = $_POST['password']; 
 require_once('dbconnect.php');  
 $sql = "SELECT password FROM users WHERE email = '$email'";
 $rst = mysqli_query($con, $sql);
 $hash = mysqli_fetch_row($rst);
 require_once('lib/password.php');
 if (password_verify($passwordFromPost, $hash['password'])) {
    echo 'success';
  } else {
    echo 'failure';
  }
}
?>

答案 2 :(得分:0)

您需要获取行:

<?php
    if($_SERVER['REQUEST_METHOD']=='POST'){
        $email = $_POST['email'];
        $passwordFromPost = $_POST['password']; 
        require_once('dbconnect.php');  
        $sql = "SELECT password FROM users WHERE email = '$email'";
        $hash = mysqli_query($con, $sql);
        while ($row = mysqli_fetch_row($hash)) {
            require_once('lib/password.php');
            if (password_verify($passwordFromPost, $row["password"])) {
                echo 'success';
            } else {
                echo 'failure';
            }
        }
    }
?>

参考:http://php.net/manual/en/mysqli-result.fetch-row.php