Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

php - 如何使用PHP清理用户输入?(How can I sanitize user input with PHP?)

是否有某个功能全面的功能可以很好地用于清理用户针对SQL注入和XSS攻击的输入,同时仍允许某些类型的HTML标签?

  ask by Brent translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's a common misconception that user input can be filtered.

(常见的误解是可以过滤用户输入。)

PHP even has a (now deprecated) "feature", called magic-quotes , that builds on this idea.

(PHP甚至有一个(现在已弃用的)“功能”,称为magic-quotes ,它基于此思想。)

It's nonsense.

(废话)

Forget about filtering (or cleaning, or whatever people call it).

(忘记过滤(或清洁,或任何人称呼它)。)

What you should do, to avoid problems, is quite simple: whenever you embed a string within foreign code, you must escape it, according to the rules of that language.

(为避免出现问题,您应该做的事情很简单:每当将字符串嵌入外部代码中时,都必须根据该语言的规则对其进行转义。)

For example, if you embed a string in some SQL targeting MySQL, you must escape the string with MySQL's function for this purpose ( mysqli_real_escape_string ).

(例如,如果在针对MySQL的某些SQL中嵌入字符串,则必须使用MySQL的函数对此字符串( mysqli_real_escape_string )进行mysqli_real_escape_string 。)

(Or, in case of databases, using prepared statements are a better approach, when possible.)

((或者,对于数据库,在可能的情况下,使用预备语句是更好的方法。))

Another example is HTML: If you embed strings within HTML markup, you must escape it with htmlspecialchars .

(另一个示例是HTML:如果将字符串嵌入HTML标记中,则必须使用htmlspecialchars对其进行转义。)

This means that every single echo or print statement should use htmlspecialchars .

(这意味着每个echoprint语句都应使用htmlspecialchars 。)

A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with exec , then you must use escapeshellcmd and escapeshellarg .

(第三个示例可能是shell命令:如果要将字符串(例如参数)嵌入到外部命令中,并使用exec调用它们,那么必须使用escapeshellcmdescapeshellarg 。)

And so on and so forth ...

(等等等等 ...)

The only case where you need to actively filter data, is if you're accepting preformatted input.

(您需要主动过滤数据的唯一情况就是接受预先格式化的输入。)

For example, if you let your users post HTML markup, that you plan to display on the site.

(例如,如果您让用户发布HTML标记,那么您计划显示在网站上。)

However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.

(但是,您应该明智地不惜一切代价避免这种情况,因为无论您对其进行多么好的过滤,它始终都是潜在的安全漏洞。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...