2012-03-21 32 views
2

我做了以下我的變量保護:每次我試圖提交包含引號符號的字符串時如何提交引號(「)登錄SQL

$ad_title=htmlentities($ad_title); 
$ad_title=mysql_real_escape_string($ad_title); 
$ad_title=stripslashes($ad_title); 

但(」) - 一切在它被識別爲錯誤的SQL查詢之後。

任何人都可以讓我知道我錯過了什麼嗎?

我知道mysql_real_escape_string應該修復它,但它沒有。

+2

不聽@mikelbring該解決方案將讓你容易受到SQL注入。 – dqhendricks 2012-03-21 20:38:57

+2

@mikelbring:** NO ** addslashes是完全廢話,應該從PHP中刪除。 – 2012-03-21 20:39:06

+0

如果你使用'mysql_real_escape_string',你不需要'addslashes'(當然不是'stripslashes'。建議:閱讀文檔 – 2012-03-21 20:39:27

回答

4

你的問題是stripslashes正在取消mysql_real_escape_string的作用。

例如

starting out with: Miles O'Brien 
after m_r_e_s(): Miles O\'Brien 
after strip_slashes: Miles O'Brien 
+0

+1爲例 – 2012-03-21 20:41:15

0

從代碼中刪除第三行。

$ad_title=htmlentities($ad_title); 
$ad_title=mysql_real_escape_string($ad_title); 
2

你mysql_real_escape_string到的stripslashes後調用有效抵消了出來。

此外,你應該逃避你的HTML的東西之前對你輸出它,而不是當你將它存儲在數據庫中。

或者,您也可以使用準備好的語句,但我感覺懶解釋說,在這個答案。 (還有數以百萬計的職位上SO一下吧。)

+0

不行,對* o *懶惰:-) – 2012-03-21 20:43:05

+0

@TheNail我真的只是語法納粹倒是?哇。可悲的是,我完全意識到,to也是正確的變體。我可能只是錯過了關鍵。無論如何,你的平凡語法修正帶來樂趣。(如果你想要非常技術性,你只是寫了一個沒有大寫或標點符號的句子片段。) – Corbin 2012-03-21 20:44:38

+0

對不起,微妙的雙關是有意的,但是從你的回答中,我明白你並不真的熱衷於......再次抱歉! – 2012-03-22 07:52:08

0
$ad_title=htmlentities($ad_title); 

您可以在(立即)插入到HTML文檔,而不是一個數據庫之前...但htmlspecialchars應該足夠了。

$ad_title=mysql_real_escape_string($ad_title); 

你可以做到這一點(立即)一些字符串一起搗碎成發往MySQL的SQL語句之前......你買得多使用prepared statements and bound arguments更好。

$ad_title=stripslashes($ad_title); 

做...嗯...也許,如果你堅持有魔術引號開啓...但你做任何轉義之前...且僅當您無法打開魔術引號關閉的服務器上。

運行mysql_real_escape_string後,因爲它(主要)逆轉它的效果肯定不這樣做!

0

您添加了不應使用行

$ad_title=stripslashes($ad_title); 

。你基本上是用該行剝離SQL注入保護。刪除線,它應該沒問題。

0
<?php 
//This should be called first, but ONLY if it is required, or it will corrupt your data. 
//This must be done before you manipulate the data in any other way. 
//Generally, this is used on the data if your server has magic quotes on. 
//I've added code to detect if it is on or not. 
$ad_title = (get_magic_quotes_gpc()) ? stripslashes($ad_title) : $ad_title; 

//This line is fine, but only do it if you know it is necessary, because it is changing your data. 
//If you are doing it just because you were receiving an SQL error, I would recommend you comment this out. 
$ad_title = htmlentities($ad_title); 

//This should be the last thing you do to your data before using it in SQL. 
//This will take care of all required escaping, and protect you from SQL injection. 
$ad_title = mysql_real_escape_string($ad_title); 
?> 
+0

在將數據插入到他的數據庫之前,他不應該以HTML格式轉義數據。至於魔術引號,我絕不會使用啓用它的主機提供商。這將是一個非常強烈的信號,表明他們已經落後於PHP時代。 – Corbin 2012-03-21 20:51:19

+0

我同意@Corbin在插入數據庫之前以HTML格式轉義。它應該僅針對SQL而不是HTML進行轉義。這樣做意味着您正在存儲修改後的版本,而不是原始數據。如果您發現因某種原因需要返回,這會造成困難。至於開啓魔術引號的主機,它可能很荒謬,但許多仍然有效。我不能告訴你,因爲我在過去的十年中一直在使用專用服務器。 – 2012-03-21 21:03:11