使用password_verify登录用户

时间:2017-07-20 16:18:20

标签: php passwords

我正在为我的网站创建后端并遇到登录用户部分的问题。

用户使用以下代码使用password_hash函数注册数据库:

UserReg.php

<?php

require_once 'db.php';
$mysqli = new mysqli($host, $user, $password, $dbname);

if($mysqli -> connect_error) {
die($mysqli -> connect_erro);
}

$username = "userF";
$password = "somePass";
$token = password_hash("$password", PASSWORD_DEFAULT);

add_user($mysqli,$username, $token);

function add_user($mysqli,$username, $token) {
    $query = $mysqli->prepare("INSERT INTO users(username, password) VALUES 
    (?,?)");

$query->bind_param('ss',$username, $token);
$query->execute();
$result = $query->get_result();

if(!$result) {
    die($mysqli->error);
}
$query->close();
}

即使我插入用户名和密码,我的登录表单也会跳到空白页面。甚至没有转到登录错误消息。

的login.php

<?php

include 'db.php';

$username = $_POST['user'];
$pwd = $_POST['password'];

$sql = "SELECT password FROM users WHERE username = ?";

$stmt = $mysqli->prepare($sql); 
$stmt->execute();
$stmt->bind_result($pass);

while ($result = $stmt->num_rows()) {
    if($stmt->password_verify($pwd, $result)) {    
        echo "Your username or password is incorrect";
    } else {
        header("Location: Menu.php");  
    }
}

我缺少什么?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我认为您需要查看password_verify的工作原理。

$username = $_POST['user'];
$pwd = $_POST['password'];

$sql = "SELECT username, password FROM users WHERE username = ?";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if ($stmt->num_rows == 1) { //To check if the row exists
  if ($stmt->fetch()) { //fetching the contents of the row
    if (password_verify($pwd, $password)) {
      $_SESSION['username'] = $username;
      echo 'Success!';
      exit();
    } else {
      echo "INVALID PASSWORD!";
    }
  }
} else {
  echo "INVALID USERNAME";
}
$stmt->close();