无法获得password_verify工作(PHP,MYSQL)

时间:2018-01-01 19:29:46

标签: php mysql

我在注册脚本中设置了password_hash。无法弄清楚如何正确使用password_verify登录我的网站。

DB的屏幕截图:https://i.imgur.com/hWjRiXN.png

登录代码(说“登录错误,即使密码正确):

<?php  
    require 'db_connect.php';

    if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $query = "SELECT * FROM `member` WHERE username='$username'";

        $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
        $count = mysqli_num_rows($result);

        if (password_verify($_POST['password'],$hashword))
        {
             echo "Correct login";
        }
            else
        {
            echo "incorrect login";
        }
    }
?>

注册码(效果很好,DB连接也没有问题):

<?php
    require 'db_connect.php';

    $email = $_POST['email'];
    $username = $_POST['username'];
    $password1 = $_POST['password1'];
    $password2 = $_POST['password2'];

    if($password1 != $password2)
        header('Location: registration.html');
    if(strlen($username) > 25)
        header('Location: registration.html');

    $hashword = password_hash($password,PASSWORD_DEFAULT);

    $query = "INSERT INTO member ( username, password, email)
    VALUES ( '$username', '$hashword', '$email');";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    mysql_close();

    header('Location: login.html');
?>

1 个答案:

答案 0 :(得分:1)

从您的代码中,您似乎没有使用插入数据库的正确散列字检查$_POST['password']

变量$hashword将没有任何内容,因此password_verify失败。

获取存储在数据库中的密码值,并将其存储在$hashword变量中,然后在password_verify函数中使用它,使其按预期工作。

示例

$row = mysqli_fetch_assoc($result);
$hashword =  $row['password'];

<强>用法

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);

$row = mysqli_fetch_assoc($result);
$hashword =  $row['password'];

if (password_verify($_POST['password'],$hashword))
{
     echo "Correct login";
}
    else
{
    echo "incorrect login";
}