这段代码在 PDO 中 sql 注入安全吗?
代码(新手):
if(isset($_POST['selection']))
{
include_once 'pdo_init.php';
$params_str = str_repeat('?,',count($_POST['selection']));
$params_str = substr($params_str,0,-1);
$res = $pdo->prepare('DELETE FROM funcionario WHERE codigo in ('.$params_str.')');
if($res->execute($_POST['selection']))
{
return json_encode(array(
'success' => 1,
'msg' => 'os registros foram deletados com sucesso!'
));
} else {
return json_encode(array(
'success' => 0,
'msg' => 'nao admitimos sql-injection aqui seu safado!'
));
}
} else {
# error out
break;
}
code (newbie):
if(isset($_POST['selection']))
{
include_once 'pdo_init.php';
$params_str = str_repeat('?,',count($_POST['selection']));
$params_str = substr($params_str,0,-1);
$res = $pdo->prepare('DELETE FROM funcionario WHERE codigo in ('.$params_str.')');
if($res->execute($_POST['selection']))
{
return json_encode(array(
'success' => 1,
'msg' => 'os registros foram deletados com sucesso!'
));
} else {
return json_encode(array(
'success' => 0,
'msg' => 'nao admitimos sql-injection aqui seu safado!'
));
}
} else {
# error out
break;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
迂腐地说,不,它不是 100% 安全的(通常你可以从准备好的声明中得到这一点)。这是因为对于 MySQL,PDO 在内部模拟准备好的语句。这意味着数据被转义,因此在 PDO 中使用准备好的语句比转义没有任何好处(至少使用默认设置)。
您可以通过在连接上设置
PDO::setAttribute(PDO::ATTR_EMULATE_PREPARES, 0)
来更改此设置。MySQLi 确实使用真正的准备好的语句,所以我建议使用它。
Pedantically, no it is not 100% safe (which you typically get from prepared statements in general). That's because with MySQL, PDO emulates prepared statements internally. This means that the data is escaped, so there is no benefit to using prepared statements over escaping when it comes to PDO (with the default settings at least).
You can change this by setting
PDO::setAttribute(PDO::ATTR_EMULATE_PREPARES, 0)
on the connection.MySQLi does use true prepared statements, so I would suggest using that instead.
看起来您正在动态地进行参数化查询。
参数化查询是注入安全的。
但请记住注意 内容本身也是如此
Looks like you're dynamically making a parameterized query.
Parameterized queries are injection safe.
But remember to watch out for the content itself, too
只要允许用户删除表中的所有行,注入似乎是安全的(因为如果她愿意,她可以发送包含表中所有 codigo 的 POST)。
不可能欺骗您的查询来接触其他表。
It seems injection safe, as long as the user is allowed to delete all rows in the table (because she can send a POST with all codigo's in the table if she wants to).
It's not possible to trick your query into touching other tables.
您使用
?
和prepare
正确执行了此操作。请注意,PDO 无法保护您的一种情况是动态表/列名称。 PDO(和mysql_real_escape_string)不会转义反引号`,因此尽量不要使用动态表名或列名。You're doing it correctly using the
?
andprepare
. Note that the one situation that PDO will not protect you against is dynamic table/column names. PDO (and mysql_real_escape_string) will not esacape backticks, `, so try to never use dynamic table or column names.