2015-09-04 96 views
0

這是我的代碼:「mysqli_real_escape_string」足以避免SQL注入或其他SQL攻擊嗎?

$email= mysqli_real_escape_string($db_con,$_POST['email']); 
    $psw= mysqli_real_escape_string($db_con,$_POST['psw']); 

    $query = "INSERT INTO `users` (`email`,`psw`) VALUES ('".$email."','".$psw."')"; 

有人能告訴我,如果它是安全的,或者如果它很容易受到SQL注入攻擊或其他SQL攻擊?

+2

可能重複的[SQL注入該得到周圍的MySQL \ _REAL \ _escape \ _string()](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-實時逃生字符串) – uri2x

回答

4

有人能告訴我它是安全的還是容易受到SQL注入攻擊或其他SQL攻擊?

正如uri2x所述,請參閱SQL injection that gets around mysql_real_escape_string()

The best way to prevent SQL injection is to use prepared statements.它們將數據(您的參數)與指令(SQL查詢字符串)分開,並且不會留下任何數據空間來污染查詢結構。編制的報表解決了fundamental problems of application security之一。

對於不能使用預處理語句的情況(例如LIMIT),對每個特定用途使用非常嚴格的白名單是保證安全性的唯一方法。

// This is a string literal whitelist 
switch ($sortby) { 
    case 'column_b': 
    case 'col_c': 
     // If it literally matches here, it's safe to use 
     break; 
    default: 
     $sortby = 'rowid'; 
} 

// Only numeric characters will pass through this part of the code thanks to type casting 
$start = (int) $start; 
$howmany = (int) $howmany; 
if ($start < 0) { 
    $start = 0; 
} 
if ($howmany < 1) { 
    $howmany = 1; 
} 

// The actual query execution 
$stmt = $db->prepare(
    "SELECT * FROM table WHERE col = ? ORDER BY {$sortby} ASC LIMIT {$start}, {$howmany}" 
); 
$stmt->execute(['value']); 
$data = $stmt->fetchAll(PDO::FETCH_ASSOC); 

我認爲上述代碼對SQL注入是免疫的,即使在不明顯的邊緣情況下也是如此。如果你使用的是MySQL,確保你關閉了模擬準備。

$db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false); 
相關問題