如何清理字符串以避免SQL注入和最常见的攻击类型? (在PHP中) [英] How to cleanse a string to avoid SQL Injection and the most common types of attack? (in PHP)

查看:182
本文介绍了如何清理字符串以避免SQL注入和最常见的攻击类型? (在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, use escapeshellcmd.
  • For passing arguments to a command via system: use escapeshellargs.
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆