我创建了两个简单的函数来过滤插入的数据,然后再将其输入到 mysql 查询中。
对于表单字段(我也使用正则表达式来单独检查每个字段。
// Form filter
function filter($var)
{
// HTML is not allowed
$var = strip_tags(trim($var));
// Check magic quotes and stripslashes
if(get_magic_quotes_gpc())
{
$var = stripslashes($var);
}
// Not using it right now, is it recommended?
// $var = htmlentities($var, ENT_QUOTES);
// Escape
$var = mysql_real_escape_string($var);
// Return
return $var;
}
然后对于 id(在 URL 中发送)我正在使用这个过滤器:
// ID filter
function idfilter($idfilter)
{
// Delete everything except numbers
$idfilter = ereg_replace("[^0-9]", "", $idfilter);
// Round numbers
$idfilter = round($idfilter);
// Test if the input is indeed a number
if(!is_numeric($idfilter) || $idfilter % 1 != 0)
{
$idfilter = 0;
}
// Filter using the formfilter (above)
return filter($idfilter);
}
是否有添加或删除这些简单功能的建议?它“安全”吗?
最佳答案
您正在使用已弃用的函数作为 magic_quotes
和 ereg_*
。为了防止 Sql 注入(inject),你应该使用 prepared statement (我建议使用 PDO ),为了防止 XSS,你应该使用 strip_tags()正如你所做的那样。
关于php - 这是过滤数据和防止 SQL 注入(inject)和其他攻击的安全方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8413412/