小编典典
有人可以告诉我它是否安全或是否容易受到SQL Injection攻击或其他SQL攻击吗?
防止SQL注入的最佳方法是使用准备好的语句。它们将数据(您的参数)与指令(SQL查询字符串)分开,并且不会为数据留下任何空间污染查询的结构。准备好的语句解决了应用程序安全性的基本问题之一。
对于无法使用准备好的语句(例如LIMIT)的情况,针对每个特定目的使用非常严格的白名单是 保证 安全的唯一方法。
// This is a string literal whitelist
switch ($sortby) {
case 'column_b':
case 'col_c':
// If it literally matches here, it's safe to use
break;
default:
$sortby = 'rowid';
}
// Only numeric characters will pass through this part of the code thanks to type casting
$start = (int) $start;
$howmany = (int) $howmany;
if ($start < 0) {
$start = 0;
}
if ($howmany < 1) {
$howmany = 1;
}
// The actual query execution
$stmt = $db->prepare(
"SELECT * FROM table WHERE col = ? ORDER BY {$sortby} ASC LIMIT {$start}, {$howmany}"
);
$stmt->execute(['value']);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
我认为上面的代码即使在晦涩的情况下也不受SQL注入的影响。如果您使用的是MySQL,请确保关闭仿真准备。
$db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
2020-05-17