password_hash()不起作用

时间:2016-03-01 10:56:01

标签: php mysql

任何人都可以指导我在哪里做错了。密码散列工作正常并存储在我的数据库中但是当我尝试使用真实密码(如123)登录时,它没有登录我。谢谢!

    <?php
        // registration script
        if (isset($_POST['submit'])) {

            $user_name = $_POST['username'];
            $user_email = $_POST['email'];
            $user_pass = $_POST['password'];

            $query = "SELECT * FROM users where Email = '" . $_POST["email"] . "'";
            $result = $obj->run_query($query);

            if ($count = mysqli_num_rows($result) == 0) {

                $query = "INSERT INTO users (Name, Email, Pass) VALUES('" . $user_name . "', '" . $user_email . "', '" . password_hash($user_pass, PASSWORD_DEFAULT) . "')";
                $result = $obj->run_query($query);

                echo "<script>alert('You have successfully Registered!')</script>";
                echo "<script>window.open('welcome.php','_self')</script>";

            } else {

                echo "<script>alert('This user email $user_email is already exist!')</script>";
            }
        }

    // login script
    if (isset($_POST['login'])) {

        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = password_hash($_POST['pass'], PASSWORD_DEFAULT);


        $query = "SELECT * FROM users WHERE Email = '$email' AND Pass = '$password'";
        $result = $obj->run_query($query);

        if ($count = mysqli_num_rows($result) > 0) {

            $_SESSION['email'] = $email;
            $_SESSION['name'] = $name;

            echo "<script>window.open('welcome.php','_self')</script>";

        } else 

        {
            echo "<script>alert('Your email or password is incorrect!')</script>";
        }

    }

?>

2 个答案:

答案 0 :(得分:2)

您需要自己更正SQL注入问题,这只是为了演示如何使用// login script if (isset($_POST['login'])) { $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['pass']; $query = "SELECT * FROM users WHERE Email = '$email'"; $result = $obj->run_query($query); if ($count = mysqli_num_rows($result) > 0) { $row = $result->fetch_object(); if (password_verify($password, $row->Pass)) { $_SESSION['email'] = $email; $_SESSION['name'] = $name; echo "<script>window.open('welcome.php','_self')</script>"; } else { echo "<script>alert('Your email or password is incorrect!')</script>"; } } else { echo "<script>alert('Your email or password is incorrect!')</script>"; } }

{{1}}

答案 1 :(得分:1)

这不能起作用:

 $query = "INSERT INTO users (Name,Email,Pass) VALUES ('$user_name','$user_email', md5('$user_pass'))";

试试这个:

$query = "INSERT INTO users (Name, Email, Pass) VALUES('" . $user_name . "', '" . $user_email . "', '" . password_hash($user_pass, PASSWORD_DEFAULT) . "')";

password_hash函数为您提供了使用BCRYPT算法加密的哈希值。见这里:http://php.net/manual/en/function.password-hash.php

这非常容易受到SQL注入攻击。你应该自己读一下如何预防它们。搜索“参数化查询”!