简体   繁体   English

我的简单 PHP 登录脚本没有按预期工作,我不知道为什么

[英]my simple PHP login script is not working as intended and i can't figure out why

so i'm trying to write a script that fetches info from MYSQL and then compares the username and password entered by the user and if they match just prints "login successful" and then "welcome back "username"".所以我正在尝试编写一个从 MYSQL 获取信息的脚本,然后比较用户输入的用户名和密码,如果它们匹配,则只打印“登录成功”,然后“欢迎返回”用户名“”。

i have to use some kind of a loop to make sure that all rows are retrieved from the table, however this also causes my script to work improperly, when i enter the user and pass from the first row, it works as intended but when i enter the second user(i have only registered two users in mysql), i get "login failed" message first then "login successful" then welcome back.我必须使用某种循环来确保从表中检索到所有行,但这也会导致我的脚本无法正常工作,当我输入用户并从第一行传递时,它会按预期工作,但是当我输入第二个用户(我只在 mysql 中注册了两个用户),我首先收到“登录失败”消息然后“登录成功”然后欢迎回来。 it seems to me the script checks the first fetched array, then the second one.在我看来,脚本检查第一个获取的数组,然后是第二个。 the problem is that i can not think of another way to write the same script.问题是我想不出另一种方法来编写相同的脚本。 could u guys help me?你们能帮帮我吗?

tried the same query without a loop, i only get the first row.在没有循环的情况下尝试了相同的查询,我只得到第一行。

<form method="post">
<input type="text" name="Username" placeholder="Username" ></input>
<input type="text" name="Password" placeholder="Password"></input>
<input type="submit" value="Login">
</form>


<?php
$login = false;
if ($_POST['Username'] && $_POST['Password'] !== "")
{
    $link = mysqli_connect("localhost" , "root" , "test" , "mahmood");
    if ($link == true)
    {
        $query = "SELECT * FROM `users`";
        $row = mysqli_query($link , $query);
        while(  $result = mysqli_fetch_array($row))
        {
            if ($result['username'] == $_POST['Username'] && $result['password'] == $_POST['Password'])
            {
                echo " login successful! "."<br>";
                $login = true;
                echo " Welcome back ".""."$_POST[Username]! ";
                die;
            } else {
                echo " wrong username or password! "."<br>";

            }
        }
        }

       else{
        echo "\n"."failed to connect to the database!"."\n";
    }

} else{echo "\n"."both username and password are required!"."\n";}



expect "login successful" and "Welcome back message" when i enter the user and pass, instead i get "login failed" then "login successful" then "welcome back"当我输入用户并通过时,期望“登录成功”和“欢迎回来消息”,而不是“登录失败”然后“登录成功”然后“欢迎回来”

You are looping the result and on each iteration, if the login/password doesn't match, you display an error message, that's why you are getting X number of login failed before seeing success.您正在循环结果,并且在每次迭代中,如果登录名/密码不匹配,则会显示一条错误消息,这就是为什么您在看到成功之前获得 X 次登录失败的原因。

In the success part, you used a boolean variable that is set to true.在成功部分,您使用了设置为 true 的 boolean 变量。 Use it !用它 !

while(  $result = mysqli_fetch_array($row))
{
    if ($result['username'] == $_POST['Username'] && $result['password'] == $_POST['Password'])
    {
        echo " login successful! "."<br>";
        $login = true; // <--------------- use this !
        echo " Welcome back ".""."$_POST[Username]! ";
        die;
    }
}
if (!$login)
{
    echo " wrong username or password! "."<br>";
}

This will fix your current code, however, you shouldn't loop over the whole list of users.这将修复您当前的代码,但是,您不应遍历整个用户列表。

What if you have 1 billion users.如果你有 10 亿用户怎么办。 You will do 1 billion of iteration before realizing login/password is wrong.在意识到登录名/密码错误之前,您将进行 10 亿次迭代。

Plus, this is consuming a lot of bandwith (and unnecessary power, think green .) to fetch all informations from the users table.另外,这会消耗大量带宽(以及不必要的功率,想想绿色。)从用户表中获取所有信息。

You'd rather use a WHERE clause to filter the results.您宁愿使用WHERE子句来过滤结果。 I suppose the username are unique.我想用户名是唯一的。 Using a WHERE clause on the username will fetch 0 or 1 result which will greatly improve performance.在用户名上使用WHERE子句将获取0 或 1 个结果,这将大大提高性能。

// Prepare the query, bind the parameters and execute it
$query = "SELECT password FROM `users` WHERE username = ?";
$stmt = mysqli_prepare($link , $query);
mysqli_stmt_bind_param($stmt, "s", $_POST['Username']);
mysqli_stmt_bind_result($stmt, $password);
// There will be only 1 loop since username should be unique
while (mysqli_stmt_fetch($stmt))
{
    if ($_POST['Password'] == $password)
    {
        $login = true;
        // success
    }
}
mysqli_stmt_close($stmt);

if (!$login)
{
    // failure
}

For more informations about prepared queries, read the official documentation有关准备好的查询的更多信息,请阅读官方文档


$result['password'] == $_POST['Password'] this piece of code shows that your passwords are stored in plain text. $result['password'] == $_POST['Password']这段代码表明你的密码是以纯文本形式存储的。 This is a very bad practice !这是一个非常糟糕的做法

Passwords should be hashed.密码应该被散列。

When registering a user in DB, the password could be hashed using password_hash() :在数据库中注册用户时,可以使用password_hash()对密码进行哈希处理:

$hashedPasswoed = password_hash($PlainTextPassword, PASSWORD_DEFAULT);

When a user log in, to compare the passwords, you use password_verify() :当用户登录时,要比较密码,您可以使用password_verify()

// $password being the hashed password stored in database
if (password_verify($_POST['password'], $password))
{
    $login = true;
    // success
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM