我有一个用于检查用户名/密码的PHP页面:
foreach($_REQUEST as $k=>$v){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT password FROM authentication WHERE username='$k'";
$result = $conn->query($sql);
$sql2 = "SELECT owner FROM listofowners WHERE owner='$k'";
$result2 = $conn->query($sql2);
if ($result->num_rows > 0) {
// output data of each row
$row = mysqli_fetch_assoc($result);
if ($row["password"] == '$v') {
if ($result2->num_rows > 0) {
echo "successfulowner";
break;
} else {
echo "successfulguest";
break;
}
} elseif($row["password"] != '$v') {
echo "wrong password";
}
} else {
echo "No such email as:" .$k;
}
$conn->close();
}
?>
尽管输入了正确的密码,我仍然收到错误的密码信息。
我做错了什么?
答案 0 :(得分:2)
你比较错误
$row["password"]!='$v'
试试这样: -
$row["password"]!= $v
你提到$ v string本身
而且你也没有比较用户名。请遵循相同的方法。
答案 1 :(得分:1)
假设您 $ _ REQUEST 的内容如下:
"username" = "name_of_the_user"
"password" = "123456"
此代码可以验证它们:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stAuth = $conn->prepare("SELECT password FROM authentication WHERE username=?");
$stAuth->bind_param("s", $_REQUEST["username"]);
$stAuth->execute();
$stAuth->bind_result($password);
if ($stAuth->fetch()) {
if ($_REQUEST["password"] == $password) {
$stOwner = $conn->prepare("SELECT owner FROM listofowners WHERE owner=?");
$stOwner->bind_param("s", $_REQUEST["username"]);
$stOwner->execute();
$stOwner->bind_result($owner);
if ($stOwner->fetch()) {
echo "successfulowner";
break;
} else {
echo "successfulguest";
break;
}
$stOwner->close();
} else {
echo "wrong password";
}
} else {
echo "No such email as:" . $_REQUEST["username"];
}
$stAuth->close();
$conn->close();
您的代码易受SQL注入攻击,我的代码可以更好。看看SQL injection和input validation如何制作更好的代码!!
您的原始代码假设$ _REQUEST将用户名作为密钥,这通常不常见,所以认为代码的逻辑错误。
答案 2 :(得分:0)
如评论中所述,它是变量'$v'
在双引号括起来的较长字符串中,如在查询行中,单引号不会影响解析中的变量,但是它们自己使它不再是变量,而是静态字符串{{ 1}}如果密码字面上是$v
答案 3 :(得分:0)
从变量$v
中删除单引号。它是一个变量而不是一个保持你的价值的字符串。因此,在您的条件语句中,无论您在何处编写类似'$v'
的代码,都要删除代码中的引号。
试试这个:
$row["password"]!=$v
并且
$row["password"]==$v