password_verify is returning true

Ale*_*das 1 php mysql hash mysqli

I want to compare my password and my hash password with password_verify() but always returns true.Why is that happening?

Here is the code:

if($_SERVER["REQUEST_METHOD"] == "POST") {
    // username and password sent from form 

    $myusername = mysqli_real_escape_string($db,$_POST['username']);
    $mypassword = mysqli_real_escape_string($db,$_POST['password']); 
    $hash = password_hash($mypassword, PASSWORD_DEFAULT);

    $ourdb = "SELECT handle FROM qa_users WHERE handle = '$myusername' and passhash = '$mypassword'";
    $ourresult = mysqli_query($db,$ourdb);
    $ourrow = mysqli_fetch_array($ourresult,MYSQLI_ASSOC);
    $ouractive = $ourrow['active'];
    $ourcount = mysqli_num_rows($ourresult);

    if(password_verify($mypassword, $hash)){
        echo "hashed";
    }
Run Code Online (Sandbox Code Playgroud)

Qir*_*rel 7

您当前正在执行的操作是对密码进行哈希处理(您首先对其进行了转义;在更改哈希值时,您不应转义密码),然后将其与您刚刚哈希化的值进行匹配/验证,而不使用数据库中的哈希值-因此它将永远匹配。等同于设置一个变量$a = 'foo';,然后检查if ($a == 'foo')-检查将始终返回true。

而是根据用户名从数据库中获取哈希值,并将其用作的第二个参数password_hash()

也,

  • 不要与数据库中的哈希进行比较,获取它,然后通过它运行 password_verify()
  • 使用准备好的语句(而不是标准query()方法和using real_escape_string())-请参阅如何防止在PHP中进行SQL注入?
if($_SERVER["REQUEST_METHOD"] == "POST") {
    $stmt = $db->prepare("SELECT passhash FROM qa_users WHERE handle = ?");
    $stmt->bind_param("s", $_POST['username']);
    $stmt->execute();
    $stmt->bind_result($hash);
    $stmt->fetch();

    if (password_verify($_POST['password'], $hash)) {
        echo "Valid login";
    } else {
        echo "Invalid login";
    }
    $stmt->close();
}
Run Code Online (Sandbox Code Playgroud)