这是一种安全的过滤数据和防止sql注入和其他攻击的方法吗?


Is this a safe way to filter data and prevent SQL-injection and other attacks?

我创建了两个简单的函数,用于在插入到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_quotesereg_*。为了防止Sql注入,你应该使用准备好的语句(我建议使用PDO),为了防止XSS,你应该使用strip_tags(),因为你正在做

在查询中使用参数而不是连接字符串。

过滤器和清洁剂通常不够安全。

如果您使用的是整数id,则可以安全地将idFilter()剥离为

function idfilter($idfilter) {
  return (int)$idfilter;
} 

正如其他人所建议的那样,使用参数化查询是正确的方法。