【问题标题】:Password can be use once密码可以使用一次
【发布时间】:2021-06-17 08:08:29
【问题描述】:

我已经在 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>";
    }
}

?>

谢谢。

【问题讨论】:

标签: php passwords sql-delete


【解决方案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 替换为 = ""

【讨论】:

  • 谢谢你,非常感谢你的帮助。
猜你喜欢
  • 2018-11-07
  • 1970-01-01
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多