清理 URL 变量的简洁方法?
我想知道在我使用它们之前是否有一个快速且简单的函数来清理我的网址中的获取变量。(或 $_POST 来考虑它......)
我想我可以使用正则表达式来替换非-允许的字符,但我有兴趣听听人们用什么来做这种事情?
I'm wondering if there is a quick and easy function to clean get variables in my url, before I work with them.( or $_POST come to think of it... )
I suppose I could use a regex to replace non-permitted characters, but I'm interested to hear what people use for this sort of thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
清理输入的概念对我来说从来没有多大意义。 它基于这样的假设:某些类型的输入是危险的,但实际上不存在危险输入这样的东西; 只是错误处理输入的代码。
其罪魁祸首是,如果您将变量嵌入某种字符串(代码)中,然后由任何类型的解释器对其进行评估,您必须确保该变量被正确转义。 例如,如果您在 SQL 语句中嵌入字符串,则必须引用并转义该字符串中的某些字符。 如果您在 URL 中嵌入值,则必须使用
urlencode
对其进行转义。 如果您在 HTML 文档中嵌入字符串,则必须使用htmlspecialchars
进行转义。 等等等等。尝试预先“清理”数据是注定失败的策略,因为此时您无法知道数据将在哪个上下文中使用。 net/magic_quotes" rel="noreferrer">magic_quotes PHP 的反特性,就是这种误导性想法的一个典型例子。
The concept of cleaning input never made much sense to me. It's based on the assumption that some kinds of input are dangerous, but in reality there is no such thing as dangerous input; Just code that handles input wrongly.
The culprit of it is that if you embed a variable inside some kind of string (code), which is then evaluated by any kind of interpreter, you must ensure that the variable is properly escaped. For example, if you embed a string in a SQL-statement, then you must quote and escape certain characters in this string. If you embed values in a URL, then you must escape it with
urlencode
. If you embed a string within a HTML document, then you must escape withhtmlspecialchars
. And so on and so forth.Trying to "clean" data up front is a doomed strategy, because you can't know - at that point - which context the data is going to be used in. The infamous magic_quotes anti-feature of PHP, is a prime example of this misguided idea.
我使用 PHP 输入过滤器 和函数 urlencode。
I use the PHP input filters and the function urlencode.
正则表达式可能很有帮助,PHP 5.2.0 还引入了一个完整的 filter 扩展,专门用于过滤不同格式的输入变量方法。
很难推荐一个单一的解决方案,因为输入变量的性质是如此......可变。 :-)
Regular expressions can be helpful, and also PHP 5.2.0 introduced a whole filter extension devoted to filtering input variables in different ways.
It's hard to recommend a single solution, because the nature of input variables is so... variable. :-)
我使用下面的方法来清理输入以供 MYSQL 数据库使用。 总而言之,通过 foreach 迭代 $_POST 或 $_GET 数组,并通过 DBSafe 函数传递每个 $_POST 或 $_GET 来清理它。 DBSafe 可以轻松修改以用于数据变量的其他用途(例如 HTML 输出等)。
I use the below method to sanitize input for MYSQL database use. To summarize, iterate through the $_POST or $_GET array via foreach, and pass each $_POST or $_GET through the DBSafe function to clean it up. The DBSafe could easily be modified for other uses of the data variables (e.g. HTML output etc..).