哈希密码并使用相同的变量进行验证

时间:2016-10-25 04:23:34

标签: php hash passwords

我尝试创建此注册页面更安全,然后我添加此密码代码

$pas_usr = mysqli_real_escape_string($koneksi, $_POST['pas_usr']);
$pas_usr = password_hash($pas_usr, PASSWORD_BCRYPT);

结果是在密码列中加密

然后在登录页面,当我试图验证它说错了密码

这是我的登录页面:

//memulai session baru
session_start();

//memanggil koneksi
include "koneksi.php";

$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);  
$password = stripslashes($password);  
$username = mysqli_real_escape_string($koneksi, $username);  
$password = mysqli_real_escape_string($koneksi, $password);  
$hashquery = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM `user` WHERE log_usr = '$username'"));
$hash=$hashquery['hash'];

if(password_verify($password, $hash)){

$query = mysqli_query($koneksi, "SELECT * from user WHERE log_usr='$username'");
$exitCount=mysqli_num_rows($query);
    if($exitCount==1){
            $data = mysqli_fetch_array($query);
            $id = $data["log_usr"];
            $lvl = $data["sts_usr"];

            if ($lvl=='A')
            {
                $link = 'index.html';
            }
            elseif($lvl='U')
            {
                $link = 'index.php';
            }
        $_SESSION['username'] = $username;
        header ("location:$link");
        exit();
    }else{
        echo "<script>alert('Username dan Password tidak valid.'); window.location = 'index.php'</script>";
    }
}else{
    echo "<script>alert('Username dan Password tidak valid.'); window.location = 'index.php'</script>";
}

1 个答案:

答案 0 :(得分:0)

当您在两个参数中使用普通密码进行检查时,

password_verify会将您的普通密码与您给定密码的哈希版本进行匹配。 password_verify的工作原理如下:

password_verify($plainPassword, $hashedPassword)

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>