我正在尝试为用户名,密码组合编写一个简单的验证练习,它将验证输入并向用户指出他们的错误,我得到一个奇怪的结果,我无法理解为什么。
如果用户有一个名为密码的密码,那么代码会验证,但如果他们的密码为 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>
答案 0 :(得分:2)
你缺少引号:
...`='$username' AND `Password` = $password"
^-- ^--
没有它们,您将在查询中插入一个单词,MySQL将其视为字段名称。鉴于taht'password`有效,请记住
Password = password
将是有效的sql,“这个字段等于它自己”。
你想:
... AND `Password` = '$password`
注意引号。
您对SQL injection attacks也是 WIDE ,因此请停止使用此代码,直到您了解了问题以及如何避免此问题为止。您的实际问题源于此注入漏洞。