PHP 登录使用错误的用户名和密码

标签 php mysql authentication

我在使用一个非常简单的 PHP 登录脚本时遇到了一个非常烦人的问题。问题是即使使用错误的用户名和/或密码登录也能正常工作。我在适用于 Linux 的 XAMPP 7.0.8 中运行它。顺便说一句,数据库“login”的表“users”只有一行。

我一直在努力理解这些脚本是如何工作的,所以我尝试了最基本的登录方式。但这对我来说一直是个谜,到现在为止我永远无法解决。

这是 PHP 部分:

<?php

    session_start();

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


        $db = mysqli_connect("localhost", "root", "", "login");

        $username = strip_tags($_POST['username']);
        $password = strip_tags($_POST['password']);

        $username = stripcslashes($username);
        $password = stripcslashes($password);

        $username = mysqli_real_escape_string($username);
        $password = mysqli_real_escape_string($password);

        $sql = "SELECT * FROM users WHERE username = '$username' LIMIT 1";
        $query = mysqli_query($db, $sql);
        $row = mysqli_fetch_array($query);
        $id = $row['id'];
        $db_password = $row['password'];

        if($password == $db_password){
            $_SESSION['username'] = $username;
            $_SESSION['id'] = $id;
            header("Location: index.php");
        } else {
            echo "Error: the information is not correct.";
        }


    }
?>

这里是 HTML 表单:

<!DOCTYPE html>
    <html lang="es">
    <head>
        <meta charset="UTF-8">
        <title>Client's area</title>
    </head>
    <body>
            <form method="post" action="">
                    <input type="text" name="username">
                    <input type="password" name="password">
                    <input class="login" type="submit" name="login" value="Login">
            </form>
    </body>
    </html> 

编辑:这篇文章的想法从来不是试图制作一个安全的登录脚本,而是为了了解一些 PHP 特性。我认识到将此代码的任何部分用于实际登录项目都是不安全的。

最佳答案

你可以使用一个简单的查询

$sql = "SELECT * FROM users WHERE username = '$username' and password= '$password'";
 $query = mysqli_query($db, $sql);
if(mysqli_num_rows($query) > 0)
{
  //Records matched process further
  $_SESSION['username'] = $username;
  $_SESSION['id'] = $id;
  header("Location: index.php");
  exit();
 } else {
   //Record not found throw error
   echo "Error: the information is not correct.";
 }

希望对你有帮助

关于PHP 登录使用错误的用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39255548/

相关文章:

c# - 当我从数据库表中删除所有行时,GridView 不显示

Mysql 原子 id 增量

c# - PHP 控制 C# 应用程序的 MySQL 数据库

java - 重置 : Chaining multiple routers with different authentication methods

javascript - 如何使用 anchor 标签触发 Stripe 信用卡结账?

php - 获取最后更新记录的id

php - 如果用户在数据库中有有效的 ID,我该如何注册用户?

php - Magento - 以编程方式保存静态 block 内容

c# - 登录前的表单例份验证登陆页面

authentication - 连接到 Azure 以创建应用程序注册