2012-10-24 27 views
0

表和列的名稱不能使用PDO綁定 - > bindParam(),但我確信不止一個人會喜歡能夠。這有點晚了,但我早先寫了這個,到目前爲止它的工作。我對PHP很陌生,想知道你的想法,以及它是否安全。是這種動態(列與表)PHP選擇查詢安全嗎?

$type = "defaultTableName"; 
$sortBy = "defaultColumnName"; 
$orderBy = "ASC"; 

//whitelisting unsafe input 
if(isset($_GET['orderBy'])&&($_GET['orderBy']=="ASC"||$_GET['orderBy']=="DESC")) 
    $orderBy = $_GET['orderBy']; 
$tableNames = array("defaultTableName", "tableName2", "tableName3"); 
$unsafeType= $_GET['type']; <---unsafe input 
$unsafeSortBy = $_GET['sortBy']; <---unsafe input 

try { 
    $pdo = new PDO("mysql:host=$hostname;dbname=$database", $username, $password); 
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    //if input is not valid this will use default table to render a table in html. 
$stmt = $pdo->prepare("DESCRIBE $type"); 
$stmt->execute(); 
$table_fields = $stmt->fetchAll(PDO::FETCH_COLUMN); 

//Whitelisting user input against table names (will require table names updates) 
    if (in_array($unsafeType, $tableNames)) { 
    $stmt = $pdo->prepare("DESCRIBE $unsafeType"); 
    $stmt->execute(); 
    $table_fields = $stmt->fetchAll(PDO::FETCH_COLUMN); 

///Whitelisting the column name to sort by against the description of the table. 
     if (in_array($unsafeSortBy, $table_fields)) { 
     $stmt = $pdo->prepare("SELECT * FROM $unsafeType ORDER BY $unsafeSortBy $orderBy"); 
    } 
    else { 
     $stmt = $pdo->prepare("SELECT * FROM $type ORDER BY $sortBy $orderBy"); 
    } 
} else { 
    $stmt = $pdo->prepare("SELECT * FROM $type ORDER BY $sortBy $orderBy"); 
} 
    $stmt->execute(); 
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 
} catch(PDOException $e) { 
    echo 'ERROR: ' . $e->getMessage(); 
} 

我看到的唯一問題是當您更改表格時,您將需要添加/刪除/更改表名稱數組。我有一個小型/中型應用程序,不是很複雜。

注意:我也是可編輯在stackoverflow,所以如果你知道一種方法,使其更好,繼續前進,編輯或讓我知道。

回答

3

不,這不安全。您直接將用戶提交的數據放入查詢字符串中。 ANYTIME你這樣做,你很容易受到SQL注入攻擊。

但是,由於您無法爲這些特定值使用佔位符,因此您必須使用pdo::quote(例如,

$safeType = $pdo->quote($_GET['type']); 

僅僅因爲它是表名或排序子句值並不意味着它不能被注入。任何進入未被引用/轉義或通過佔位符插入的字符串的用戶數據都是攻擊媒介。

+0

我終於明白了......在我開始驗證之前。它可以逃脫。 – Juan