简体   繁体   English

Php登录密码_verify

[英]Php login password_verify

I am learning how to use prepared statements and I thought I would try out a login system (simple) using the password_hash() and password_verify( ) functions. 我正在学习如何使用预处理语句,我想我会尝试使用password_hash()password_verify( )函数登录系统(简单)。 I have succesffuly inserted data in using prepared statemernts, now I wish to verify the password and do something with the user. 我已成功使用准备好的状态数据库插入数据,现在我希望验证密码并对用户执行某些操作。

I seem to be getting back my fail message at this stage: 我似乎在这个阶段收回了我的失败信息:

$stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ?");
$stmt->bind_param('s', $username);

$username = $_POST['ulogin'];
$password = $_POST['upassword'];

$stmt->execute();
$stmt->bind_result($username, $password);



$row = $stmt->fetch();
if ($stmt->num_rows == 1) {
    if (password_verify($password, $row['user_password'])) {
        echo 'success';
    }
} else {
 echo "Wrong data";
}

$stmt->close();
$conn->close();

If I do a var_dump($stmt->fetch()); 如果我做一个var_dump($stmt->fetch()); and the login username is correct is comes back as bool(true) 并且登录用户名是正确的以bool(true)

Im not sure how to attempt to verify the password now. 我不知道如何尝试验证密码。

<?php

$stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ?");
$stmt->bind_param('s', $username);

$username = $_POST['ulogin'];
$password = $_POST['upassword'];

$stmt->execute();
$stmt->bind_result($username, $password);
$row = $stmt->fetch(); //fetch DB results


if (!empty($row)) { // checks if the user actually exists(true/false returned)
    if (password_verify($_POST['upassword'], $row['password'])) {
        echo 'success'; // password_verify success!
    } else {
    echo 'failed';
    }
} else {
    echo "This user does not exist"; //email entered does not match any in DB
}

$stmt->close();
$conn->close();

You do not necessarilly need to check for number of rows. 您无需检查行数。 Also have an else statement if the password is not verified for any reason 如果由于任何原因未验证密码,也要有else语句

This is one of your problems: 这是你的一个问题:

$password = $_POST['upassword'];
...
$stmt->bind_result($username, $password);
...
if (password_verify($password, $row['user_password'])) {

You are overwriting your $password variable so it is no longer the posted value. 您正在覆盖您的$password变量,因此它不再是已发布的值。

Using the POST value should solve the problem: 使用POST值可以解决问题:

 if (password_verify($_POST['upassword'], $row['user_password'])) {

or 要么

 if (password_verify($_POST['upassword'], $password)) {

as you have bound the password from the result to that variable. 因为您已将结果中的密码绑定到该变量。

Also, if your username in the database is unique, you can replace: 此外,如果数据库中的用户名是唯一的,则可以替换:

$row = $stmt->fetch();
if ($stmt->num_rows == 1) {

with: 有:

if ($row = $stmt->fetch()) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM