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条回答 默认 最新

  • duanqing3026 2015-09-29 11:01
    关注

    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 )){
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建