This question already has an answer here:
这个问题在这里已有答案:
- How can I prevent SQL injection in PHP? 28 answers
如何在PHP中阻止SQL注入? 28个答案
i am using PDO package to manage my application database. i use PDO::prepare
, PDOStatement::execute
and somtimes PDO::quote
, PDO::query / PDO::exec
to excute my queries
我正在使用PDO包来管理我的应用程序数据库。我使用PDO :: prepare,PDOStatement :: execute和somtimes PDO :: quote,PDO :: query / PDO :: exec来执行我的查询
are PDO::prepare
and PDO::quote
completely secure? or shoud i make more work to properly validate my inputs.not only for databaase but for php code either Thank you
PDO :: prepare和PDO :: quote完全安全吗?或者shoud我做了更多的工作来正确验证我的输入。不仅仅是数据库,但PHP代码或者谢谢你
1 个解决方案
#1
2
There's nothing magic about using prepare()
. You can interpolate unsafe variables into a string and then prepare that string. Boom—SQL injection. Preparing a statement doesn't make it safe.
使用prepare()并没有什么神奇之处。您可以将不安全的变量插入到字符串中,然后准备该字符串。 Boom-SQL注入。准备一份声明并不能确保安全。
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = {$_POST['id']}"); // UNSAFE!
What makes it safe is using parameters.
什么使它安全是使用参数。
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = ?");
$stmt->execute([$_POST['id']]); // SAFE!
Naturally, people say "use prepared statements" because you must use prepared statements to use parameters. But just saying "use prepared statements" kind of misses the point, and some developers get the wrong understanding.
当然,人们会说“使用预准备语句”,因为您必须使用预准备语句来使用参数。但只是说“使用准备好的陈述”有点遗漏了这一点,而且一些开发人员得到了错误的理解。
The PDO quote() method is also safe, but I find it simpler and easier to use parameters.
PDO quote()方法也是安全的,但我发现使用参数更简单,更容易。
$idQuoted = $pdo->quote($_POST['id']);
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = $idQuoted");
#1
2
There's nothing magic about using prepare()
. You can interpolate unsafe variables into a string and then prepare that string. Boom—SQL injection. Preparing a statement doesn't make it safe.
使用prepare()并没有什么神奇之处。您可以将不安全的变量插入到字符串中,然后准备该字符串。 Boom-SQL注入。准备一份声明并不能确保安全。
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = {$_POST['id']}"); // UNSAFE!
What makes it safe is using parameters.
什么使它安全是使用参数。
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = ?");
$stmt->execute([$_POST['id']]); // SAFE!
Naturally, people say "use prepared statements" because you must use prepared statements to use parameters. But just saying "use prepared statements" kind of misses the point, and some developers get the wrong understanding.
当然,人们会说“使用预准备语句”,因为您必须使用预准备语句来使用参数。但只是说“使用准备好的陈述”有点遗漏了这一点,而且一些开发人员得到了错误的理解。
The PDO quote() method is also safe, but I find it simpler and easier to use parameters.
PDO quote()方法也是安全的,但我发现使用参数更简单,更容易。
$idQuoted = $pdo->quote($_POST['id']);
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = $idQuoted");