Verify hashed password from database

旧巷老猫 提交于 2021-02-11 15:36:34

问题


I am currently letting users sign up with a username and password and storing the password hashed in my database which is stored fine as follows:

//Signing up
<?php
    $user = $_POST['user1'];
    $pass = $_POST['pass1'];
    $pass = password_hash($pass, PASSWORD_DEFAULT);     
    mysql_query("INSERT INTO users(username, password) VALUES ('$user', '$pass')");
?>

<html>
    <body>
        <h1>Signup</h1>
        <form action="new_user.php" method="POST">
            <p>Username: </p><input type="text" placeholder="User name" name="user1"/>
            <p>Password: </p><input type="password" placeholder="Password" name="pass1"/>
            <br><br>
            <input type="submit" value="Signup!"/>
        </form>
    </body>
</html> 

Using the following code to verify the hashed password against the user's password input but it doesn't work. Returns the message as invalid info1. I tried to echo the information from $result2 and was expecting the information to be the hashed password something like '$2y$10$lRgHiIV5Qddt9'. Instead I am getting the message "Resource id #7". Am I retrieving the information wrongly? Please assist.

//Verifying
<?php
    $myUserName = $_POST['user'];
    $myPassword = $_POST['pass'];

    //prevent SQL injections
    $myUserName = stripslashes($myUserName);
    $myPassword = stripslashes($myPassword);

    $query1 = "SELECT * FROM users WHERE username='$myUserName'";
    $result1 = mysql_query($query1);
    $count1 = mysql_num_rows($result1);

    if($count1 == 1){
        $query2 = "SELECT password FROM users WHERE username='$myUserName'";
        $result2 = mysql_query($query2);
        //echo $result2; //Testing to see if am getting the hashed password. 
        if(password_verify($myPassword, $result2 )){
            $seconds = 120 + time();
            setcookie(loggedIn, date("F js - g:i a"), $seconds);
            header("location:login_success.php");
        }
        else{
            echo "Invalid info1";
        }
    }
    else{
            echo "Invalid info2";
    }
?>

回答1:


In this line

if(password_verify($myPassword, $result2 )){

the variable $result2 is supposed to be a string, but it is a resource. You should extract the string inside the column password inside the first row in the resource, and use that string in the password_verify function.

Something like:

$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$hash = $row['password'];
if(password_verify($myPassword, $hash )){



回答2:


You need to fetch value from resource

$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$password = $row['password'];
if(password_verify($myPassword, $password )){

}


来源:https://stackoverflow.com/questions/32842118/verify-hashed-password-from-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!