如何清理字符串以避免SQL注入和最常见的攻击类型? (在PHP中) [英] How to cleanse a string to avoid SQL Injection and the most common types of attack? (in PHP)
问题描述
有没有办法在尽可能少的代码中过滤SQL注入和最常见的攻击形式的字符串?
在我的脚本我正在使用以下内容,我想知道它是否合理安全以及其他人是否有建议:
$ cleanName = htmlspecialchars(addslashes($ dirtyName));
看看我如何过滤html字符和引号和双引号。
$ b
注意:我正在使用 addslashes()
而不是 mysql_real_escape_string()
因为我不想将我使用的数据库硬编码到我的代码中。
这样可以吗?
预先感谢
可能不是...您需要以分别为每个目的转义您的原始文本,您将使用它:
- 对于GET请求,使用
urlencode
。 - 对于HTML输出,使用
htmlentities
。
- 对于通过
system
调用命令,使用escapeshellcmd
。 - 通过
system
使用escapeshellargs
。 - 传递数据库参数:使用
mysql_real_escape_string
。
没有通用解决方案神奇地逃离文本。保留原始文本内部,并为适当的目的转义。
Is there a way to, in as little code as possible, to filter a string for both SQL injection and the most common forms of attack?
In my scripts I'm using the following, I would like to know whether it's reasonably safe and whether someone else has a suggestion:
$cleanName = htmlspecialchars(addslashes($dirtyName));
See how I filtered it both for html chars and for quotes and double-quotes.
NOTE: I'm using addslashes()
rather than mysql_real_escape_string()
because I don't want to hardcode the DB I'm using into my code.
Is this ok?
Thanks in advance
Probably not... you need to escape your raw text for each purpose separately for which you are going to use it:
- For GET requests, use
urlencode
. - For HTML output, use
htmlentities
. - For calling as a command via
system
, useescapeshellcmd
. - For passing arguments to a command via
system
: useescapeshellargs
. - For passing a database parameter: use
mysql_real_escape_string
.
There's no "universal" solution for magically escaping text. Keep raw text internally, and escape it for the appropriate purpose.
这篇关于如何清理字符串以避免SQL注入和最常见的攻击类型? (在PHP中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!