0

我正在尝试为用户名、密码组合编写一个简单的验证练习,该练习将验证输入并向用户指出他们的错误所在,我得到一个奇怪的结果,我无法理解为什么。

如果用户有一个名为Password的密码,则代码将验证,但是如果他们的密码为Password1,那么即使我在数据库中更改了用户名和密码组合,我也会收到用户名和密码组合不正确的响应。

以前会有人遇到过这个问题吗?我该如何解决?

    <html>
    <head>
        <title>Login</title>
        <link rel="stylesheet" type="text/css" href="style.css"/>
    </head>
    <body>
         <h1>Log In</h1>
        <form action="login.php" method="post">
            <ul id="login">
                <li> Username: <br />
                    <input type ="text" name="username"/>
                </li>
                <li>
                    Password: <br/>
                    <input type="password" name="password"/>
                </li>
                <li>
                    <input type="submit" value="Log In"/>
                </li>

                <li>
                    <a href="Registration.php">Register</a>
                </li>
            </ul>

<?php


   $username = $_POST['username'];
    $password = $_POST['password'];
function user_exists($username){
$server = 'localhost';
$user='root';
$password='';
$db = 'finance_checker';

$mysqli = mysqli_connect($server, $user, $password, $db);

if(mysqli_connect_errno($mysqli)){
    echo "Failed to connect to MySQL".mysqli_connect_error();
}
$res = $mysqli->query("SELECT * FROM `users` WHERE `UserName` = '$username'");

return ($res->num_rows>0);
$res->close();
}
function userLogin ($username, $password){
$server = 'localhost';
$user='root';
$pass='';
$db = 'finance_checker';

$mysqli = mysqli_connect($server, $user, $pass, $db);
    $res = $mysqli->query("SELECT * FROM `users` WHERE `UserName`='$username' AND `Password` = $password");
    if($res&&$res->num_rows>0){
        return true;;
       }else{

        return false;
    }
}


if(empty($_POST)==false){

    if(empty($username)==true ||empty($password)==true){
        echo "Please complete both sections of the form!<br />";
    } else if(empty($username)==true){
            echo "You must enter a username!<br />";
    } else if(empty ($password)==true){
            echo "You must enter a password!<br />";
    } else if (user_exists($username)==false){
        echo "Username cannot be found. Click on the register link to create a new account.";  
    } else{
    $login = userLogin($username, $password);


    if($login == false){
        echo 'Username and Password combination is not compatible!';

    } else{

        header("Location:home.php ");
        }        
    }
}

?>
    </body>
</html>
4

1 回答 1

2

您缺少引号:

...`='$username' AND `Password` = $password"
                                 ^--       ^--

如果没有它们,您将在查询中插入一个裸词,MySQL 会将其视为字段名称。鉴于“密码”有效,请记住

Password = password

将是有效的 sql,“该字段等于自身”。

你要:

... AND `Password` = '$password`

注意引号。

您也对SQL 注入攻击开放态度,因此在您了解该问题以及如何避免该问题之前,请停止处理此代码。您的实际问题源于此注入漏洞。

于 2013-10-20T21:25:29.033 回答