如何在此代码中修复SQL注入?
由于
function safeQuery($query) {
$db = new SQLite3(dirname(__FILE__) . "/private/database.db") or die ("Unable to open database");
SQLite3::escapeString($query);
$result = $db->query($query);
$row = $result->fetchArray();
$db->close();
return $row;
}
function areUserAndPasswordValid($user, $password) {
$query = "SELECT count(*) FROM userTable WHERE username = '$user' AND password = '$password'";
$row = safeQuery($query);
$count = $row[0];
return $count > 0;
}
function getFileList($user) {
$query = "SELECT fileId, filename, createdBy, owner FROM filesTable WHERE owner = '$user'";
$db = new SQLite3(dirname(__FILE__) . "/private/database.db") or die ("Unable to open database");
$result = $db->query($query) or die ("Unable to execute query");
$rows = array();
while($row=$result->fetchArray()){
$rows[] = $row;
}
$db->close();
return $rows;
}
答案 0 :(得分:2)
您应始终使用预准备语句,而不是直接将用户输入传递到查询中。
将SELECT count(*) FROM userTable WHERE username = '$user' AND password = '$password'
替换为以下内容:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
(该代码段取自http://php.net/manual/en/pdo.prepared-statements.php)
预备语句将阻止用户注入SQL。
有关其他一些有用的答案,请参阅How can I prevent SQL injection in PHP?。