如何在PHP中清除POST和GET变量以进行XSS和SQL注入 [英] how to clean POST and GET vars in PHP for XSS and SQL injection
问题描述
在我的网络应用程序中是一个配置文件,其中包括数据库连接设置,并始终在PHP脚本的第一行加载。我想包含一个函数,它清除所有POST和GET数据,可能存在现有的XSS和SQL注入风险。
In my web app is a config file which includes i.e. database connection settings ans is always loaded at the first line of a PHP script. I would like to include a function which cleans all POST and GET data for maybe existing XSS and SQL Injection risks.
我不确定该功能是否足够
I am not sure if that function is really enough
function make_safe($variable)
{
$variable = strip_tags(mysql_real_escape_string(trim($variable)));
return $variable;
}
foreach ($_POST as $key => $value) {
$_POST[$key] = make_safe($value);
}
//Same for $_GET & $_SESSION
您对这个问题有什么建议吗?
Do you have recommendation for this problem?
推荐答案
此功能:
function make_safe($variable)
{
$variable = strip_tags(mysql_real_escape_string(trim($variable)));
return $variable;
}
无法使用
SQL注入和XSS是两种不同的野兽。因为它们每个都需要不同的转义,所以你需要分别使用每个转义函数strip_tags和mysql_real_escape_string。
加入它们会破坏每个的安全性。
SQL injection and XSS are two different beasts. Because they each require different escaping you need to use each escape function strip_tags and mysql_real_escape_string separatly. Joining them up will defeat the security of each.
在将数据输入数据库时使用标准的mysql_real_escape_string()。
在将数据输出到屏幕之前查询数据库时使用strip_tags()。
Use the standard mysql_real_escape_string() when inputting data into the database. Use strip_tags() when querying stuff out of the database before outputting them to the screen.
为什么组合这两个函数是危险的
来自马口: http://php.net/manual/en/function.strip- tags.php
Why combining the two function is dangerous From the horses mouth: http://php.net/manual/en/function.strip-tags.php
因为 strip_tags()
实际上并未验证HTML,部分或损坏的标签可以导致删除比预期更多的文本/数据。
Because strip_tags()
does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.
因此,通过将错误的html输入数据库字段,智能攻击者可以使用您的天真实现来击败<$ c你的组合中有$ c> mysql_real_escape_string()。
So by inputting malformed html into a database field a smart attacker can use your naive implementation to defeat mysql_real_escape_string()
in your combo.
这篇关于如何在PHP中清除POST和GET变量以进行XSS和SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!