PHP pasword_verify 总是说密码有效,除非列为空

PHP pasword_verify always saying password is valid except if column is empty

我不是 100% 确定我使用 PHP 密码验证正确,因为它总是说从表单输入的密码有效。我认为我的代码部分有问题:

include('../connection/conn.php');
            $stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($db_email, $db_password);
            $count = $stmt->num_rows;
            //password hasing
            if ($count == 1)
            {
                while ($stmt->fetch()) {
                    if (password_verify($password, $db_password))
                    {
                        echo "Sucess";
                    }
            }
            }

我会添加 conn.php 文件内容,以防万一有人需要它

    <?php 
global $conn;
$server = "localhost";
$user = "root";
$password = "";
$db = "loginV2";
$conn = mysqli_connect($server, $user, $password, $db);

if (mysqli_connect_errno())
  {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
{

    echo "<p id='connection'>True</p>";
}

?>

无论我在表单中输入什么密码,"Success" 都会回显到是否输入正确密码的页面。这是 html 形式:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post"  name="input_form" onsubmit="return validateForm()">
                <label>Email:</label><br>
                <input type="text" name="email">
                <p class="error" id="email_Err"><?php echo $emailErr ?></p>
                <label>Password:</label>
                <input type="password" name="password">
                <p class="error" id="password_Err"><?php echo $passwordErr ?></p>
                <input type="submit" value="Sign Up">
            </form> 

我的错误可能是愚蠢的,但我已经尝试从 PHP 手册中学习 password_verify 和 password_hash,据我所知,这段代码应该可以工作。即使写得不好,也应该起作用。任何帮助,将不胜感激。谢谢。

编辑:

除了我的 mqysli_connect 之外,所有这些代码都在一个 PHP 文件 "login.php" 中。我将在下面插入全部代码:

    <!DOCTYPE html>
<html>
    <head>
        <title>Login</title>
        <link rel="stylesheet" type="text/css" href="style.css" >
        <link href="https://fonts.googleapis.com/css?family=Nunito:200" rel="stylesheet">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
            function validateForm()
            {
                var email = document.forms["input_form"]["email"].value;
                var password = document.forms["input_form"]["password"].value;
                var valid = true;
                if (email == null || email == "")
                    {
                        document.getElementById("email_Err").innerHTML = "Email is a required field";
                        valid = false;
                    }
                if (password == null || password == "")
                    {
                        document.getElementById("password_Err").innerHTML = "Password is a required field";
                        valid = false;
                    }

                if (valid === false)
                    {
                        $(function()
                         {
                            $( ".form_container" ).effect("shake");
                        });
                    }
                return valid;
            }

            $(function()
            {
                $('.form_container').hide().slideDown('slow');
            });
        </script>
    </head>

    <body>

        <?php 

        $email = $password = "";
        $emailErr = $passwordErr = "";
        $otherErr = "";
        if ($_SERVER["REQUEST_METHOD"] == "POST")
        {
            $dataErr = false;
            if (empty($_POST["email"]))
            {
                $emailErr = "Email is a required field";
                $dataErr = true;
            }
            else
            {
                $email = input($_POST["email"]);
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $emailErr = "Invalid email "; 
                    $dataErr = true;
                }
            }

            if (empty($_POST["password"]))
            {
                $passwordErr = "Password is a required field";
                $dataErr = true;
            }
            else
            {
                $password = $_POST["password"];
                if (strlen($password) < 8)
                {
                    $passwordErr = "Invalid Entry";
                    $dataErr = true;
                }
            }


           //Suspected problem here 

        if (!$dataErr)
        {
            include('../connection/conn.php');
            //Duplicate Check
            $stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($db_email, $db_password);
            $count = $stmt->num_rows;
            //password hasing
            if ($count == 1)
            {
                while ($stmt->fetch()) {
                    if (password_verify($password, $db_password))
                    {
                        echo "Sucess";
                    }
            }
            }
        }   
        }

        function input($data) 
        {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }






        ?>
        <div class="form_container">
            <h2>Login</h2>
            <!--  -->
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post"  name="input_form" onsubmit="return validateForm()">
                <label>Email:</label><br>
                <input type="text" name="email">
                <p class="error" id="email_Err"><?php echo $emailErr ?></p>
                <label>Password:</label>
                <input type="password" name="password">
                <p class="error" id="password_Err"><?php echo $passwordErr ?></p>
                <input type="submit" value="Login">
            </form>
            <?php echo "<p style='text-align: center; color: red;'> " . $otherErr . "</p>" ?>
        </div>


    </body>
</html>

再次感谢

我刚刚在我自己的数据库上测试了一些东西,发现以下内容适用于我的数据库 table:

$conn = mysqli_connect(...blah blah blah);
$email = "my_email_here";

$stmt = $conn->prepare("SELECT email, password FROM my_table_here WHERE email=?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one, $two);

while ($stmt->fetch()) {
    var_dump($one); // my email from database
    var_dump($two); // my hashed password from database (looks something like y$VmfW7/b1t4SVxi7wlxjZmu8...)
}

除了您问题中的 sql 查询,不确定这里有什么不同。


编辑

您可以尝试的是:

$password = 'testing';
$hashed = password_hash($password, PASSWORD_DEFAULT);

if (password_verify($password, $hashed) {
    echo "password verified";
} else {
    echo "not verified";
}

用上面的代码替换你的 while 语句,看看得到了什么回应

发现错误。 var_dumps 6 小时,问题出在 conn.php

include('../connection/conn.php');
            //Duplicate Check
            $stmt = $conn->prepare("SELECT email, password FROM users WHERE email=?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($db_email, $db_password);
            $stmt->fetch();

在验证密码之前,我们包含 conn.php 连接数据库的密码。这包括我的数据库密码具有变量名称作为用户输入密码:

    <?php 
    global $conn;
    $server = "localhost";
    $user = "root";
// $password is set to nothing
    $password = "";
    $db = "loginV2";
    $conn = mysqli_connect($server, $user, $password, $db);

    if (mysqli_connect_errno())
      {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    else
    {

        echo "<p id='connection'>True</p>";
    }

    ?>

这意味着当执行 password_verify 时它正在比较来自 conn.php 的 $password,它是空白的。更改变量以连接到数据库解决了问题。