2013-04-01 53 views
0

长话短说,我有一个管理部分,用户可以从多个下拉列表中选择必须查询以获取某些值的表和字段。因此,在Zend中查询是通过连接字符串在ZEND中引用原始数据库以避免sql注入

$query = "SELECT $fieldName1, $fieldName2 from $tableName where $fieldName1 = $value"; 

我怎样才能逃避使用Zend的方法来避免SQL注入上述执行?我试图将它们全部添加为?并调用quoteinto但似乎这不适用于某些变量(如表名或字段名称)

回答

0

使用quoteInto()或Zend_db_Select :: where()作为值,以及表和列名称,我会简单地去除所有非alpha字符,然后在将它们用于SQL之前将它们包装在` quotes中。

例子:

// Strip non alpha and quote 
$fieldName1 = '`' . preg_replace('/[^A-Za-z]/', '', $fieldName1) . '`'; 
$tableName = '`' . preg_replace('/[^A-Za-z]/', '', $tableName) . '`'; 
// .... 

// Build the SQL using Zend Db Select 
$db->select()->from($tableName, array($fieldName1, $fieldName2)) 
       ->where($fieldName1 . ' = ?', $value); 
2

ZF有quoteIdentifier()专门为此:

$query = "SELECT ".$db->quoteIdentifier($fieldName1).","... 

你的情况,你可能(还)要核对有效列名的白名单。

0

在SafeMysql你可以把它简单,因为

$sql = "SELECT ?n, ?n from ?n where ?n = ?s"; 
$data = $db->getAll($sql,$fieldName1,$fieldName2, $tableName, $fieldName1, $value); 

虽然我明白,你会不会改变你的ZF来SafeMysql。

尽管如此,还有一件事情是应该手动完成的:
我怀疑你想让用户浏览用户表或财务表或其他什么。 所以,你必须对一个允许的表数组验证一个传递的表名。

$allowed = ('test1','test2'); 
if (!in_array($tableName, $allowed)) { 
    throw new _403(); 
}