sprintf() 如何防止 SQL 注入?
我听说 sprintf()
可以防止 SQL 注入。这是真的吗?如果是这样,怎么办?
为什么人们建议这样编写查询:
$sql = sprintf('SELECT * FROM TABLE WHERE COL1 = %s AND COL2 = %s',$col1,$col2);
I have heard that sprintf()
protects against SQL injection. Is it true? If so, how?
Why people are recommending to write query like this:
$sql = sprintf('SELECT * FROM TABLE WHERE COL1 = %s AND COL2 = %s',$col1,$col2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
sprintf 不会保护你!它仅替换
%s
你必须 mysql_real_escape_string 所以:
更安全的注入
注意:我建议你看看 PDO,这是我喜欢用于 DBconections 和查询的内容
sprintf won't protect you! It only replaces the
%s
you must mysql_real_escape_string so:
is safer injection
note: I suggest you take a look at PDO, it is what I like to use for DBconections and queries
这起不到任何保护作用。使用 sprintf 可以使代码更具可读性,然后放入和取出字符串以对每个变量运行 mysql_real_escape_string ……但该示例最后并没有转义变量这样就失去了优势。
如果您想要适当的保护,请使用提供绑定参数的东西。
That doesn't do any protection. Using
sprintf
makes for more readable code then dropping in and out of a string to runmysql_real_escape_string
over each of the variables … but that example doesn't escape the variables at the end so that advantage is lost.If you want decent protection, use something that provides bound parameters.
使用 sprintf 可以防止数字字段的 SQL 注入:
通过以这种方式使用 sprintf,您可以确保 $col1 将被转换为整数——尽管如果它不是真正的整数,它可能会生成错误或警告。
防止 SQL 注入的正确方法是检查所有输入值并进行转义。但这在其他问题中有更全面的介绍,因此我不打算在这里详细介绍。
Using sprintf might protect against SQL injection for numeric fields:
By using sprintf in this way, you can be sure that $col1 will be converted to an integer--although it might generate an error or warning, if it's not truly an integer.
The proper way to protect against SQL injection is to check all of your input values, and do escaping. But that's much more thoroughly covered in other questions, so I'm not going to go into detail here.
显然不是,如果您实际上在书籍或教程中读过它,您应该自动丢弃它以供将来参考。
然而,它可能是生成需要进一步处理的输出的实用方法。请比较:
这同样适用于其他类型的输出,例如 SQL 代码,但当然您仍然需要做一些输入以使其安全:sprintf() 只是一个常规字符串函数,不支持 SQL 和数据库。
请注意,绑定参数使用类似的语法:
这就是为什么我特别发现提供这种语法的数据库库(例如 PDO)更容易使用。
It obviously doesn't and if you've actually read that in a book or tutorial you should automatically discard it for future reference.
However, it can be a practical way to generate output that needs further processing. Please compare:
Same applies to other kind of output, such as SQL code, but of course you still need to do something to input in order to make it safe: sprintf() is just a regular string function that's unaware of SQL and databases.
Please note that bind parameters use a similar syntax:
That's why I particularly find easier to use those DB libraries that provide this syntax, such as PDO.