2011-01-13 85 views
4

是從SQL注入這個代碼100%安全:這是一個安全的方法來防止SQL注入?

$id = $_GET['id'] 
mysql_query('SELECT * FROM mytable WHERE id < ' . (int)$id); 

還是我必須這樣做?

$id = $_GET['id'] 
mysql_query('SELECT * FROM mytable WHERE id < ' . mysql_real_escape_string($id)); 
+0

你的第二個代碼塊中有一個SQL注入漏洞,因爲你沒有從一倍`mysql_real_escape_string引用輸出()`。 – Johan 2011-05-29 21:03:26

回答

2

查詢仍然可以炸燬如果$_GET['id']是空的,或者(int)$_GET['id']計算結果爲空。您最終會在查詢中出現語法錯誤。盲目逃避或鍵入一個值並將其填充到查詢中是不夠的。你必須檢查最終的「安全」價值實際上是安全的,而不僅僅是奶奶的一件狼。

0

我用sprintfmysql_query(sprintf('SELECT * FROM mytable WHERE id < %d', $id));

+0

這不是很安全,因爲如果$ id不是int,它將被轉換爲int。其中如果$ ID = 「XYZ」,那麼這將是 「SELECT * FROM mytable的WHERE ID <0」 – 2011-01-13 18:43:47

+0

@Amir Raminfar:他說,以防止SQL注入,這一點也適用。演員在這個時刻並不是我想的問題。 – Cesar 2011-01-13 18:48:36

+1

不,它不工作,因爲如果它是DELETE * FROM MYTABLE WHERE ID>%d,那麼我可以通過它只是在做ID> 0不太好刪除一切! – 2011-01-13 19:17:57

-1

它是安全的,但你可能想要做

if(is_int($id)){ 
mysql_query('SELECT * FROM mytable WHERE id < ' . mysql_real_escape_string($id)); // just to be safe always to escape 
} 
2

mysql_query('SELECT * FROM mytable WHERE id < ' . mysql_real_escape_string($id)); 

是不好的做法。如果你希望它是一個字符串,至少引用字符串:

mysql_query('SELECT * FROM `mytable` WHERE `id`<"'.mysql_real_escape_string($id)).'"'; 

(同時你在它,報價所有現場和表名以及,對於像id可能是或成爲保留關鍵字在一些點)

我寧願投,如果它是一個整數。字符串版本的一個說法是,有一天id可能是字母數字的(在很多網站上越來越頻繁地出現)。

0

您應該使用參數化查詢。那麼你不必擔心所有逃跑。它也使得SQL更易於閱讀。哦,不要使用select *,只需選擇你想要的。

0

你必須這樣做沒有

$id = mysql_real_escape_string($_GET['id']); 
//put the escaped string in a $var, so your select statement stays readable 
//this will help in debugging, and make **not** forgetting those vital quotes 
//easier. 
$query = "SELECT * FROM mytable WHERE id < '$id'"; 
//          ^ ^always single quote your $vars 
//  ^         ^and double quote the query 
$result = mysql_query($query); 
//and test to see if your query ran successful. 
if (!$result) { //your query gave an error, handle it gracefully. 

然後你是安全的。