2012-11-09 61 views
0

這可能是常見的事情,但我有一個問題。允許撇號,同時仍然保持mysql_real_escape_string()標記。mysql_real_escape_string(),但允許帶撇號的名字

我有這樣的:$name = stripslashes(mysql_real_escape_string($_POST['stadium_name']));

,我測試它這樣的:

$getInfoX = mysql_fetch_array(mysql_query("SELECT * FROM `stadiums` WHERE `stadium_name` = '$stadium_name'")) or die(mysql_error()); 

我可以做一個例子注入像x'; DROP TABLE members; --或類似Stade de l'Aube撇號的名稱...但撇號名稱讓我像一個錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Aube'' at line 1

我該怎麼辦?

+2

使用PDO或mysqli的,[閱讀文章的詳細信息:防止SQL注入的最佳方式(http://stackoverflow.com/questions/60174/best-way-to -prevent-sql -injection) –

+0

mysql_real_escape_string會爲你處理。你得到的錯誤是從MySQL而不是PHP是嗎? – case1352

+0

爲什麼你在'mysql_real_escape_string'已經爲你逃脫之後仍然在剝離斜線? – Gapton

回答

3

您鏈接mysql_real_escape_stringstripslashes的結果,基本上刪除了所有爲安全原因添加的所有內容mysql_real_escape_string

所以,如果你有$stadium_name= "Fred's Stadium";輸入mysql_real_escape_string($stadium_name)返回"Fred\'s Stadium"可以納入你的查詢安全產生

例如MySQL查詢。在mysql_real_escape_string輸出調用stripslashes前面刪除\的'所以你發送的查詢

"SELECT * FROM `stadiums` WHERE `stadium_name` = 'Fred's Stadium'" 

到MySQL認爲你的字符串爲‘弗雷德’其次是一些垃圾(可以變成是危險的)。

解決方案是使用單獨的變量來存儲mysql_real_escape_string的結果,因爲它在數據庫查詢中的使用是正確的,但不適合顯示給用戶。

我希望這會有所幫助。

問候

TC

+0

因此,使用mysql_real_escape_string存儲它,但是在顯示時使用strip_slashes? – nn2

+0

是的,並且在回顯它之前使用php.net/htmlentities,這樣你就不會將HTML注入到你的頁面中。 – TheConstructor

1

你的問題是這樣的:

$name = stripslashes(mysql_real_escape_string($_POST['stadium_name'])); 

stripslashes()撤消逃逸。

您可能已經看到該函數用作magic_quotes的解決方法。如果你要申請它,那麼請在之前這個數據庫轉義函數。