密码_验证,PDO

时间:2017-01-28 16:54:20

标签: php password-hash

我的哈希密码(b-crypt)有问题。我在用户注册方面成功完成了这项功能:$hashed = password_hash($password, PASSWORD_DEFAULT);。但我不知道如何在我的代码中实现这行代码password_verify($password, $hashed_password)

这是用户类的一部分:

class User{
    private $db;
    public function __construct() {
        $this->db = new Database(); 
    }

public function getLoginUser($email, $password){
        $sql = "SELECT * FROM tbl_user WHERE email = :email AND password = :password LIMIT 1";
        $query = $this->db->pdo->prepare($sql);
        $query->bindValue(':email', $email);
        $query->bindValue(':password', $password);
        $query->execute();
        $result = $query->fetch(PDO::FETCH_OBJ);
        return $result;
    }

    public function userLogin($data){
        $email    = $data['email'];
        $password = $data['password'];
        $chk_email = $this->emailCheck($email);

        if ($email == "" OR $password == "") {
            $msg = "<div class='alert alert-danger'><strong>Error! </strong>Field must not be Empty!</div>";
            return $msg;
        }   

        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            $msg = "<div class='alert alert-danger'><strong>Error! </strong>The E-mail address is not valid!</div>";
            return $msg;
        }

        if ($chk_email == false) {
            $msg = "<div class='alert alert-danger'><strong>Error! </strong>The E-mail address Not Exist!</div>";
            return $msg;
        }

        if (password_verify('password', $hashed)) {
            echo 'Password is valid!';
        } else {
            echo 'Invalid password.';
        }

        $result = $this->getLoginUser($email, $password);   

        if ($result) {
            Session::init();
            Session::set("login", true);
            Session::set("id", $result->id);
            Session::set("name", $result->name);
            Session::set("username", $result->username);
            Session::set("loginmsg", "<div class='alert alert-success'><strong>Success! </strong>You are Logged In!</div>");
            header("Location: index.php");
        } else {
            $msg = "<div class='alert alert-danger'><strong>Error! </strong>Data not found!</div>";
            return $msg;
        }
    }   

这是我的login.php,其函数为userLogin($ _ POST);

<?php
$user = new User();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {
    $usrLogin = $user->userLogin($_POST);
}

有人可以帮我解决这个问题吗?如果你可以为我编写代码(段),将会很有帮助。

谢谢你和

Reegards!

1 个答案:

答案 0 :(得分:0)

您使用password_hash将散列密码存储到数据库

$hashed = password_hash($password, PASSWORD_DEFAULT);

在您的登录页面上,您需要根据用户的电子邮件从数据库中检索旧的哈希密码,然后根据发布的密码进行检查

$password = $_POST['password'];
if (password_verify($password, $hashed_password_from_database)) {
   // login
} else {
   // error login failed
}