Php登录系统密码哈希&密码验证

时间:2017-02-27 20:22:28

标签: php system password-protection

我尝试使用password_hash()password_verify()创建一个登录系统(已完成注册系统),但它并不适用于我。我整个上午一直试图找到答案,但似乎无法使其发挥作用,我已经看过编程课程,阅读博客文章,什么都没有。我最关注的教程是one

<!-- login -->
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
    $errors = array();
    error_reporting(E_ALL); 
    ini_set('display_errors', 1);

    //Basic validation
    if(empty($_POST['username'])){
        $errors[] = "Please enter your username";
        }else{
        $username = $mysqli->real_escape_string($_POST['username']);
        }

            if(empty($_POST['password'])){
            $errors[] = "Please enter your password";
            }else{
            $password = trim($_POST['password']);
            }

            if (empty($errors)) {
            $sql = "SELECT * FROM users WHERE username = '$username'";
            $result = $mysqli->query($sql);
            if ($result->num_rows === 1) {
            $row = $result->fetch_array(MYSQLI_ASSOC);
            if(password_verify($password, $row['password'])) {
                echo 'test';
            $_SESSION['user']['user_id'] = $row['user'];
            header("Location: google.com");
            exit();
            }else{
            $errors[] = "The username or password do not match";
            }
            }else{
            $errors[] = "The username or password do not match";
            }
        }
}
?>
<!-- register -->
<?php
    if($_SERVER['REQUEST_METHOD'] == "POST") {
        $username = mysqli_real_escape_string($conn, $_POST['username']);
        $password = $_POST['password'];
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $confirm_password = mysqli_real_escape_string($conn, $password);
        $ip = $_SERVER['REMOTE_ADDR'];

        if(empty($username) || empty($password) || empty($confirm_password)) {
            $error = "Fill in the missing fields";
        } else {
            $sql = "INSERT INTO users VALUES('', '$username', '$hashed_password', '$ip', 'User')";
            if($conn->query($sql) === TRUE) {
                $error = "Your account has been created.";
            } else {
            $error = "Your account has not been created, please try again later.";  
        } 
    }
}
?>

最终结果产品应该成功登录并重定向,我使用PHP 5.6并在localhost XAMPP上运行。

1 个答案:

答案 0 :(得分:1)

因为你正在使用

,所以永远不会得到匹配
 $password =mysqli_real_escape_string($conn, $_POST['password']); 

存储密码,然后在验证时不使用它。而是使用

$password = trim($_POST['password']);

确保您 values of disabled inputs will not be submited? 或在散列之前使用其他任何清理机制。这样做更改密码并导致不必要的额外编码。 password_hash()函数可以生成一些非常冗长的文本(当前默认值为60个字符),因此请确保数据库中的字段足够大以容纳哈希值。现在将字段设置得更大将允许所需的长度。 PHP团队正在为该方法添加更多算法,这意味着哈希可以并且将会增长。