用户输入数据库
假设我们只期望用户发送的数据包含字符串或数字。使用 ereg 和 preg_match 函数检查数据是否足够安全?有办法伪造它们吗?我们还应该使用 mysql_real_escape_string 吗?
Suppose that, we're expecting just strings or numbers with the data send by a user. Is it safe enough to check the data with ereg and preg_match functions? Is there a way to fake them? Should we still use mysql_real_escape_string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将是简短的答案...
使用PDO:
例如Zendfamework正在使用这个引擎。
This will be short answer...
Use PDO:
For example Zend famework is using this engine.
是否安全是相对于你自己的需求而言的。如果您出于某种原因想避免 mysql_real_escape_string 那么我首先想问为什么。
我的答案是:当然...根据您的条件,
您可以预匹配 [0-9a-z] 并且没有什么可担心的。为了安全起见,请尝试传递多字节字符。只要您的条件不允许您在匹配不符合您的要求时做任何事情,那么据我所知,就没有什么棘手的解决方法可以在如此严格的规则下插入恶意字符。
但“弦”这个词是非常开放的。这包括标点符号吗?如果您允许标准注入字符作为您所谓的“字符串”,那么我的答案不再确定。
但我仍然推荐对所有用户提交的信息使用 mysql_real_escape_string() ,无论您如何事先尝试净化它。
safe enough is relative to your own needs. If you're wanting to avoid mysql_real_escape_string for some reason then I first want to ask why.
My answer is: sure... depending on your conditions
you can preg match against [0-9a-z] and there is nothing to fear. Try passing a multibyte character to be safe. So long as your condition does not allow you to do anything if the match does not fit your requirements then there is no tricky work-around that I know of to slip in malicious characters on such a strict rule.
but the term "string" is very open. does that include punctuation? what kind, etc. If you allow standard injection characters as what you call a "String" then my answer is no longer sure.
But I still recommend mysql_real_escape_string() on all user submitted info, no matter how you try to purify it before hand.
如果您使用正则表达式来匹配有效输入并且成功,则用户输入有效。话虽这么说,如果有效输入中没有任何恶意字符(特别是引号或潜在的多字节字符),那么您不需要调用 mysql_real_escape_string 。同样的原则也适用于以下情况:
因此,如下所示:
一旦
preg_match
成功,在 SQL 查询中使用$subject
是可以的/安全的。If you use a regex to match against valid input, and it succeeds, then the user input is valid. That being said, if you don't have any malicious characters in valid input (particularly quotes or potentially multibyte characters), then you don't need to call
mysql_real_escape_string
. The same principle applies to something like:So something like the following:
It is fine / safe to use
$subject
in an SQL query once thepreg_match
succeeds.