2013-11-25 67 views
0

對於我的表單提交,每當有單引號或雙引號時,報價後面的所有文本在正在發送的$ _POST ['p#']中被截斷。我已經試過htmlspecialchars,用$#039替換字符串,然後用addslashes,但$ _POST數組中的字符串仍然被截斷。這裏是代碼的相關部分,當$ ques有一個帶有單引號的字符串時,就會出現問題。如何在表單提交後的表單中轉義引號?

 "<form action="some.php" method="post"><input type='checkbox' name='p".$numberOfProgrammingQuestion."' value='".$ques."'>".$ques."<br><br>"; 
+1

它只會在這裏猜測,而不會看到您的PHP代碼處理它。你可以發佈嗎? – Justin

回答

1

基礎上還有什麼以下應該工作....

"<form action="some.php" method="post"><input type='checkbox' name='p".$numberOfProgrammingQuestion."' value='".htmlspecialchars($ques, ENT_QUOTES)."'>".htmlspecialchars($ques, ENT_QUOTES)."<br><br>"; 

通知的HTML特殊字符標誌ENT_QUOTES。它的文件讀取....

int 
$flags 
[optional] 
A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401. 
Available flags constants 
Constant Name 
Description 
ENT_COMPAT 
Will convert double-quotes and leave single-quotes alone. 
ENT_QUOTES 
Will convert both double and single quotes. 
ENT_NOQUOTES 
Will leave both double and single quotes unconverted. 
ENT_IGNORE 
Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it may have security implications. 
ENT_SUBSTITUTE 
Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#38;#FFFD; (otherwise) instead of returning an empty string. 
ENT_DISALLOWED 
Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#38;#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content. 
ENT_HTML401 
Handle code as HTML 4.01. 
ENT_XML1 
Handle code as XML 1. 
ENT_XHTML 
Handle code as XHTML. 
ENT_HTML5 
Handle code as HTML 5. 
+0

我不認爲這裏的問題實際上是圍繞字符編碼,而是由於OP構建輸出字符串的糟糕方式導致他試圖預先填充到要輸入的元素中的數據破碎。 –

+0

我之前使用過htmlspecialchars($ ques),忽略了有更多的參數可以用來使它更好地工作。它現在完美運行,謝謝威爾! – Garvin

+0

我應該措辭或只顯示代碼的輸入行,以更多地關注我遇到的實際問題,因爲代碼必須讓人誤解問題所在,對於Mike而言很抱歉。 – Garvin

0

如果你以一致的方式使用雙引號和單引號,你的生活會好得多。通常,您應該總是圍繞HTML元素屬性值使用雙引號。這幾乎是一個行業標準。所以請記住,我通常喜歡在PHP中回顯HTML元素時使用單引號。我只是使用長時間的概念,很清楚我在哪裏投入動態價值觀。這也可以防止需要擔心轉義報價。

我的建議是改變你的代碼如下:

echo '<form action="some.php" method="post"><input type="checkbox" name="p' . $numberOfProgrammingQuestion . '" value="' . $ques . '">' . $ques . '<br><br>'; 

注意,即使使用的StackOverflow的最基本語法高亮是多麼清楚地看到靜態字符串以及其中動態值。將它與原始文章中的語法突出顯示進行比較。你可以看到你對雙引號和單引號的不一致使用是如何產生問題的。

所以,我的建議,如你所知,應該是在編輯器中工作,具有良好的語法高亮功能。這將有助於指導您解決其中的一些問題。

+0

我的問題不在於此。我只是複製並粘貼上面顯示的錯誤代碼。問題在於,$ ques中包含的字符串有時具有單引號,當通過POST提交表單時,該引號將在引用之後切斷所有內容。接收POST的PHP會收到每個UP,直到第一個單引號(不包括)。 – Garvin

+0

@Garvin是的,這是因爲你把像你的價值一樣的單引號括起來,比如'value ='XXXXX''這樣如果你的值本身有一個'''',你就會得到'value ='XXX'XXX''第一部分將被捕獲。現在,您肯定需要在此場景中對雙引號進行編碼。 –