登录前如何使用PHP验证密码和密码是否正确?

时间:2020-03-30 23:13:41

标签: php sql passwords

我正在使用以下脚本登录用户,此刻,用户发布电子邮件和密码,如果正确,它将使用户登录:

    <?php
/* User login process, checks if user exists and password is correct */

// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'"); 

if ( $result->num_rows == 0 ){ // User doesn't exist
    $_SESSION['message'] = "User with that email doesn't exist!";
    header("location: error.php");
}
else { // User exists
    $user = $result->fetch_assoc();

    if ( password_verify($_POST['password'], $user['password']) ) {

        $_SESSION['email'] = $user['email'];
        $_SESSION['first_name'] = $user['first_name'];
        $_SESSION['last_name'] = $user['last_name'];
        $_SESSION['active'] = $user['active'];

        // This is how we'll know the user is logged in
        $_SESSION['logged_in'] = true;

        header("location: profile.php");
    }
    else {
        $_SESSION['message'] = "You have entered wrong password, try again!";
        header("location: error.php");
    }
}

我在注册表单中添加了“ pin”列,并将其添加到数据库中,并且在注册时设置了pin,但是我正在努力获取上面的登录代码以验证输入的pin是否正确,密码也会通过POST以登录表单发送。 我已经尝试过了:

else { // User exists
    $user = $result->fetch_assoc();

    if ( password_verify($_POST['password'], $user['password']) && ( password_verify($_POST['pin'], $user['pin'])  ) {

        $_SESSION['email'] = $user['email'];
        $_SESSION['first_name'] = $user['first_name'];
        $_SESSION['last_name'] = $user['last_name'];
        $_SESSION['active'] = $user['active'];

但是我似乎无法正确理解语法,password_verify也用于哈希密码,但是该引脚未哈希。

如何在登录之前修改此登录脚本以同时检查密码和未插入的密码?

1 个答案:

答案 0 :(得分:1)

如果未对图钉进行哈希处理,则将其与字符串进行比较。

if (password_verify($_POST['password'], $user['password']) && 
      (strcmp($_POST['pin'], $user['pin']) == 0)) {
    // Do you stuff
}
相关问题