正则表达式避免用户输入注入
收到用户的输入后,我在服务器上执行以下操作(使用 PHP):
$safe_input = ereg_replace("[^A-Za-z0-9-]", "", $_GET["input"]);
然后,我使用 $safe_input 变量进行 SQL 查询,并将其打印到用户的屏幕上。
这是否可以保证不会发生任何类型的注入(SQL 注入、XSS 等)?
谢谢,
乔尔
Upon receiving an input from a user, I am doing the following on my server (with PHP):
$safe_input = ereg_replace("[^A-Za-z0-9-]", "", $_GET["input"]);
Then I am using the $safe_input variable for SQL queries and also printing it to the user's screen.
Does that guarantee that no injection of any sort (SQL injection, XSS, etc.) is possible?
Thanks,
Joel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,它的作用是确保您在
$safe_input
字符串中只允许使用 AZ(大写或小写)、数字和“-”破折号字符。理论上,您的 SQL 仍然可能会被某些人在输入中添加“--”来修改,以强制将语句的后半部分视为 SQL 注释。
像您发布的内容一样简单的内容并不是恶意代码注入的解决方案 - 当您希望允许用户发送除您明确允许的字符之外的字符时,很可能会导致出现问题。
您应该查看专门处理此类事情的第三方 PHP 库 - 有很多用于 SQL 和 XSS 预防的库。或者甚至查看服务器级别并考虑添加可用于此任务的 Apache 模块之一(当然前提是您使用的是 Apache...)。通过沿着这条路线,您将采取更全面的保护方法 - 并且您将利用该领域的专业知识,而不是尝试为您的项目重新发明这个特定的轮子。
Well, what it does is ensure that you're only allowing A-Z (upper or lower), numerics, and the "-" dash character in your
$safe_input
string.In theory, your SQL could still be munged by someone adding "--" to an input in order force the latter part of the statement to be treated as an SQL comment.
Something as simple as what you've posted is not a solution to malicious code injection - and will most likely cause you issues down the line when you want to allow a user to send characters other than the ones you've explicitly allowed.
You should look at 3rd party PHP libraries that specifically deal with this kind of thing - there are plenty out there for SQL and XSS prevention. Or even look at the server level and think about adding one of the Apache modules available for this task (providing you're using Apache of course...). By going down this route you'll be taking a much more holistic approach to protection - and you'll be leveraging expertise in this area, rather than trying to re-invent this particular wheel for your project.
首先,
ereg
系列函数已被弃用,您应该使用preg
系列函数来代替:不要限制 用户只需
A-Za-z0-9-
。我建议你去:您可以自定义接受和拒绝的内容。
有趣:
值得注意的是,Kohana CodeIgniter 的改进替代方案还支持 HTML Purifier安全。
至于SQL注入,你至少可以使用
mysql_real_escape_string
函数。更好的方法是使用准备好的语句。First of all
ereg
family of functions is deprecated, you should usepreg
family of functions instead:Don't limit users to just
A-Za-z0-9-
. I would suggest you to go for:You can customize as to what is accepted and what is rejected.
Interesting:
It is interesting to note that Kohana the improved alternative of CodeIgniter also supports HTML Purifier for security.
As for SQL injection, the least you can do is to use
mysql_real_escape_string
function. The better way is to use prepared statements though.