密码只能使用一次

时间:2021-06-17 08:08:29

标签: php passwords sql-delete

我已经在 phpMyAdmin 中为用户设置了登录密码。但我想确保一旦用户使用密码就会被删除。因此,用户不能两次登录系统。但我不知道如何为此创建 SQL 语句。我只想删除密码而不删除用户名。我可以将删除代码与提交按钮结合使用吗?

<?php 

if(isset($_POST['submit']))
{
    include("config.php");
    session_start();
    $username = $_POST['username'];
    $password = $_POST['password'];
    $_SESSION['login_user'] = $username;
    
    $query = mysqli_query($mysqli,"SELECT username from logins WHERE username='$username' and password='$password'");
    
    if(mysqli_num_rows($query) !=0)
    {
        
        echo "<script language='javascript' type='text/javascript'>location.href='home.php'</script>";
    }
    else
    {
        echo "<script language='javascript' type='text/javascript'>alert('Username or Password invalid!')</script>";
    }
}

?>

谢谢。

1 个答案:

答案 0 :(得分:-1)

在重定向用户之前添加 SQL UPDATE 语句。 并且不要将密码以纯文本形式保存在您的数据库中: Best way to store passwords in MYSQL database

但更好的主意是,您将在上次登录时向数据库添加时间戳。如果时间戳为 NULL,则用户可以登录。如果不为空,则用户无法登录。

但这里是给定代码的示例:

(安全手册:https://www.php.net/manual/en/mysqli.real-escape-string.php

if(isset($_POST['submit']))
{
    include("config.php");
    session_start();
    $username = mysqli_real_escape_string($mysqli, $_POST['username']);// add a little bit security at this point
    $password = mysqli_real_escape_string($mysqli, $_POST['password']); // add a little bit security at this point
    $_SESSION['login_user'] = $username;
    
    $query = mysqli_query($mysqli,"SELECT username from logins WHERE username='$username' and password='$password' and password IS NOT NULL"); // check that the password is not empty
    
    if(mysqli_num_rows($query) !=0)
    {
        // update your DB row
        // if you got an ID, than do it with the ID and not with the $username and $password
        mysqli_query($mysqli,"UPDATE logins SET password = NULL WHERE username='$username' and password='$password'");

        // to do it better use instead of JavaScript PHP for the redirect. In this case it is important, that nothing is printed out bevore the `header()`:
        header("Location: home.php");
        exit;

        // try to not mix it up if you are on an pure PHP page
        // echo "<script language='javascript' type='text/javascript'>location.href='home.php'</script>";
    }
    else
    {
        // same as above
        header("Location: login.php?tag=login-invalid");
        exit;
        // echo "<script language='javascript' type='text/javascript'>alert('Username or Password invalid!')</script>";
    }
}

如果“密码”不能为 NULL,则通过 = "" 替换 NULL

相关问题