使用MySQLi时如何防止SQL注入?

时间:2013-05-04 20:22:54

标签: php mysql sql mysqli code-injection

如何在这样的SQL查询中阻止SQL注入?

<?php
$mysqli = new mysqli("ip", "username", "pass", "database");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Sorry, the login server is 'Under Maintainance'");
    exit();
}

$username = $_POST["username1"];
$username = strtolower($username);
$password = $_POST['password1'];
$hash = sha1(strtolower($username) . $password);

$query = "SELECT * FROM accounts WHERE name='$username'";

if ($result = $mysqli->query($query)) {
    /* determine number of rows result set */
    $rownum = $result->num_rows;

if($rownum != 0)
{
while ($row = $result->fetch_assoc()) {
  {
  $acct = $row['acct'];
  $pass = $row['pass'];
}
if($hash == $pass){
session_start();
$_SESSION['name']=$username;
$_SESSION['acct']=$acct;
header('Location:index.php');
} else {
echo 'There was an error when logging in. Make sure your password and username are correct.';
}
}
    $result->close();
}
else
{
echo 'Account does not exist. Please <a href="register.php">Register</a> an account before logging in.';
}
    $mysqli->close();
}
?>

我已经添加了加密,但我似乎无法找到一种我知道如何使用的预防方法。此外,用户是否可以在不使用输入框的情况下使用MySQL注入? (页面解剖???)

1 个答案:

答案 0 :(得分:2)

加密和查询卫生无关。

您已经在使用mysqli,这很不错,但您没有清理查询的输入(即$username,这可能不一定是strtolower ed)。

您应该使用正确参数化的查询进行卫生处理。

$query = "SELECT * FROM accounts WHERE name = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($acct, $pass);
$stmt->fetch();
//$act and $pass are now properly set

SQL注入的限制与用户无关。您甚至可能会意外地将自己注入自己的代码中,注射甚至不必是恶意的。因此,即使您认为存在恶意注入的风险,也应始终正确地参数化您的查询。