登录脚本:两个 if 语句



这段代码工作正常,直到用户注册后我开始散列密码。我正在使用标准功能

password_hash()

这会在用户表中对我的密码进行哈希处理。但是,我注意到如果没有其他功能验证他们输入了正确的密码,他们就无法登录。它告诉我,我必须在这样的语句中使用password_verify。

if (password_verify($password, $hash)) {
// Success!
}
else {
// Invalid credentials
}

但是,我的登录脚本中已经有一个if语句,我不确定如何将两者结合起来。我试过这个:

if(isset($_POST['Login']) && (password_verify($password, $hash))){

但这也行不通。有人可以给我一个关于我能做什么的建议吗?这是我的整个登录脚本(我已经连接到数据库),我只需要为散列密码添加 if 语句。

if(isset($_POST['Login'])){

$Username = mysqli_real_escape_string($con,$_POST['Username']);
$UserPassword = mysqli_real_escape_string($con,$_POST['UserPassword']);
$sel_user = "select * from users where Username='$Username' AND UserPassword='$UserPassword'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
    if($check_user>0){
        session_start();
$_SESSION['Username']=$Username;
header('Location: index.php');
}
else {
            header('Location: login.php');
            echo "<p>". "Wrong password or username" . "</p>";
}
}

您应该使用存储在数据库中的哈希值检查用户提供的密码。所以你必须做这样的事情:

if (isset($_POST['login']) {
   //check for if password is provided
   //some code to verify user login in database and if exists get password      
   //hash for this login like this
   $query = mysqli_query($con,"select hash from users where   
   username=".$login); //or some error proccessing
   if (mysqli_num_rows($query) == 0) {
     //incorrect login proccesing
   }
   $hash = mysqli_fetch_assoc($query)['hash'];
   if (!password_verify($password,$hash)) {
    //wrong passsword proccesing
   }
}

最新更新