使用预准备语句获取哈希密码

时间:2016-09-30 16:12:08

标签: php sql

我无法让这个工作。我不熟悉准备好的陈述,所以我对我正在做的事情有点50/50。

注册后,密码将使用password_hash($pass,PASSWORD_DEFAULT)

进行哈希处理

现在,我正在努力让我的登录页面能够正常运行,但我不知道在哪里/如何使用password_verify()

来编写它
$username = $_POST['username'];
        $password = $_POST['password'];

        $sql = "SELECT * FROM users WHERE BINARY username=? AND password=?";
            $stmt = $db->prepare($sql);
                $stmt->bind_param("ss",$username,$password);
                $stmt->execute();
                $result = $stmt->get_result();
                $num_rows = $result->num_rows;

                if($num_rows == 1){

                    $rows = $result->fetch_assoc();
                    if(password_verify($password, $rows['password'])){
                    $_SESSION['loggedin'] = $username;
                    $_SESSION['country'] = $rows['country'];
                    $_SESSION['email'] = $rows['email'];
                    $_SESSION['avatar'] = $rows['u_avatar'];
                    $_SESSION['is_gm'] = $rows['is_gm'];
                    $_SESSION['user_lvl'] = $rows['user_lvl'];
                    $_SESSION['totalposts'] = $rows['post_total'];
                    $_SESSION['totalcoins'] = $rows['coins_total'];
                    $_SESSION['totalvotes'] = $rows['vote_total'];
                    $_SESSION['secquest'] = $rows['sec_quest'];
                    $_SESSION['secanswer'] = $rows['sec_answer'];
                    $_SESSION['join_date'] = $rows['join_date'];

                    header("Location: /index.php");
                    exit();
                    }
                } else {
                    echo "<p class='error_msg'>No accounts could be found with the given credentials.</p>";
                }

                $stmt->free_result();
                $stmt->close();
                $db->close();

我认为密码验证会在if($num_rows == 1)之前验证,但正如我所说,我不知道。

1 个答案:

答案 0 :(得分:1)

您的查询基本上是:

SELECT * FROM users WHERE username=username AND password_hash=plain_text_password

这不会起作用。如果您依赖于PHP密码散列,则无法在SQL级别进行密码比较。从数据库中检索密码哈希,然后在WHERE参数中执行password_verify(排除密码=?)。