-3

我已经用这个库正确地实现了哈希的创建,只改变了成本值。现在我坚持实际验证用户。对于我当前的系统,我还必须检查用户是否已激活,然后还要启动会话。这就是我所拥有的:

 <?php 
require('core/init.php');

// Required field names
$required = array('username', 'password');

// Loop over field names, make sure each one exists and is not empty
$error = false;
    foreach($required as $field) {
        if (empty($_POST[$field])) {
        $error = true;
        }
    }
//This is what will make the password 
$form_password = $_POST['password'];
$hash = password_hash($form_password, PASSWORD_BCRYPT);
    if ($error) {
        echo "Please Check username and password field!";
    }
        else { 
                if (password_verify($form_password, $hash)) {
                    $member_username = $_POST['username'];
                    $query = $dbh->prepare("SELECT * FROM users WHERE username = :user");
                    $query->bindParam(':user', $member_username);
                    $query->execute();
                    $row = $query->fetch();

                        if($row['activated'] > 0){
                            $_SESSION["user_id"] = $row['user_id'];
                            header("location: login_success.php");

                            }   else {
                                    echo "Account not activated wait for system administrator!";

                                }


                } else {
                            Echo "Wrong password or username please <a href='index.php'><bold>Retry!</bold></a>";

                        }


        }

如果密码验证实际上是真的,我所做的是运行查询。该查询然后获取激活的行以检查该值是否大于 0,如果不是,则未激活用户。

但是我的错误是,无论我输入什么,我都会收到错误的密码或用户名,请重试!

我知道密码和用户不正确。我第二次猜测自己是否正确实施了 password_compat 的验证部分。

任何帮助都会很棒。谢谢你。

编辑 :

dev-null-dweller 在评论中回答的问题。

问题:我没有意识到我不能将库 $password 和 $hash 变量用作全局变量。所以为了修复它,我创建了变量并且一切正常。谢谢你!

4

1 回答 1

3

两者$password$hash在您的代码中都未定义。至于$password你可以从$_POST,但$hash来自数据库,所以你必须在验证密码之前查询它:

if ($error) {
    echo "Please Check username and password field!";
} else {
    $member_username = $_POST['username'];
    $form_password = $_POST['password'];
    $query = $dbh->prepare("SELECT * FROM users WHERE username = :user");
    $query->bindParam(':user', $member_username);
    $query->execute();
    $row = $query->fetch();
    if (!$row || !password_verify($form_password, $row['password'])) {
        if ($row['activated'] > 0) {
            $options = array(/* Your current hashing options */);
            $algorithm = PASSWORD_BCRYPT;
            if (password_needs_rehash($row['password'], $algorithm, $options)) {
                $hash = password_hash($row['password'], $algorithm, $options);
                /* Store new hash in db */
            }
            $_SESSION["user_id"] = $row['user_id'];
            header("location: login_success.php");
        } else {
            echo "Account not activated wait for system administrator!";
        }
    } else {
        Echo "Wrong password or username please <a href='index.php'><b>Retry!</b></a>";
    }
}
于 2012-12-29T21:11:48.897 回答