doutouhe5343
2015-09-29 10:56
浏览 45
已采纳

从数据库验证散列密码

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";
    }
?>

2条回答 默认 最新

相关推荐 更多相似问题