如何使用PHP清理用户输入? [英] How can I sanitize user input with PHP?

查看:99
本文介绍了如何使用PHP清理用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某个地方是否存在一个综合功能,可以很好地清除用户输入的SQL注入和XSS攻击,同时仍然允许某些类型的HTML标记?

解决方案

常见的误解是可以过滤用户输入. PHP甚至有一个(现已不推荐使用的)功能",称为魔术引用,则以此为基础.废话忘记过滤(或清洁,或任何人称呼它).

为避免出现问题,您应该做的事情很简单:每当将字符串嵌入外部代码中时,都必须按照该语言的规则对其进行转义.例如,如果您将字符串嵌入某些针对MySQL的SQL中,则必须为此使用MySQL的函数对字符串进行转义(mysqli_real_escape_string). (或者,对于数据库,如果可能的话,使用预备语句是更好的方法.)

另一个示例是HTML:如果将字符串嵌入HTML标记中,则必须使用 .这意味着每个echoprint语句都应使用htmlspecialchars.

第三个示例可能是shell命令:如果要将字符串(例如参数)嵌入到外部命令中,并使用 escapeshellcmd escapeshellarg .

依此类推...

情况下,您需要主动过滤数据,如果您接受预格式化的输入.例如,如果您让用户发布HTML标记,则您计划显示在网站上.但是,您应该明智地不惜一切代价避免这种情况,因为无论您对其进行多么好的过滤,它始终都是潜在的安全漏洞.

Is there a catchall function somewhere that works well for sanitizing user input for SQL injection and XSS attacks, while still allowing certain types of HTML tags?

解决方案

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. 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). (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. This means that every single echo or print statement should use 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.

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. 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.

这篇关于如何使用PHP清理用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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