2013-04-01 108 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(); 
}