用户验证密码哈希

时间:2015-09-21 02:53:36

标签: php mysqli hash

好的,所以我正在尝试建立一个基本的用户身份验证系统。好吧,我已经做到了。但我现在要做的是检查用户密码是否与哈希相关。我正在使用$ hash = password_hash($ password,PASSWORD_DEFAULT);但是对于登录页面,我想在数据库中使用散列密码检查用户密码,以便他们可以登录。我怎么能这样做?

Register.php:

    <?php
include('config.php'); 

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

function mres($input){
    if (get_magic_quotes_gpc()){
        $input = stripslashes($input);
    }
    return mysqli_real_escape_string($conn, $_POST['$input']);
}

$email=mysqli_real_escape_string($conn, $_POST['email']);
$username=mysqli_real_escape_string($conn, $_POST['username']);
$password=mysqli_real_escape_string($conn, $_POST['password']);
$hash = password_hash($password, PASSWORD_DEFAULT);
$query = $conn->query("select * from users where username='$username'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
echo "User already exist redirecting in 5 seconds!";
} else {
$sql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$hash', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

$conn->close();
header("Location: ../index.php");
?>

的login.php:

<?php
session_start();
include('config.php'); 

$error=''; 

if (isset($_POST['submit'])) {
if (empty($_POST['userid']) || empty($_POST['passid'])) {
$error = "Username or Password is invalid";
}
else
{


$user=mysqli_real_escape_string($conn, $_POST['userid']);
$pass=mysqli_real_escape_string($conn, $_POST['passid']);
$hash = password_hash($pass, PASSWORD_DEFAULT);
$passv = password_verify($pass, $hash);
$query = $conn->query("select * from users where password='$passv' AND username='$user'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
$_SESSION['username']=$user;
$_SESSION['checklogin']== true;
header("location: ../profile.php"); 
} else {
$error = "Username or Password is invalid";
}
mysqli_close($conn);
}
}   
?>

(是的,我知道我在那里添加了那个我没有在注册中使用的功能。它将来使用我现在保存它。我有它的计划。)

1 个答案:

答案 0 :(得分:0)

使用用户名从数据库中选择密码。从数据库中获取哈希密码,并使用if语句使用password_verify(inputPassword,hashPassword)。