簡體   English   中英

帶有“奇怪”字符的PHP POST

[英]PHP POST with “strange” characters

因此,我創建了一個在線測試門戶。 本質上,用戶單擊他們認為此測試正確答案旁邊的單選按鈕。 然后,代碼會將字符串與他們單擊的答案進行比較,並將其與實際答案進行比較。 如果字符串不同,則將其標記為錯誤。

我有幾個問題,其中的問題中有“怪異”字符。 破折號之類的東西,甚至像雙引號一樣簡單。 看來,當用戶單擊以下答案之一時,奇怪的字符未正確發布到我的評分頁面上,因此字符串比較不起作用,並將其標記為錯誤。

我做錯了什么嗎?

這是我使用的一小段代碼...

 //Question 4 $question[$i] = 'When are steel or composite toe boots required in the field?'; $answer[$i][1] = 'Always-unless... actually, there is no “unless”'; $answer[$i][2] = 'Never-crocs are truly a groundbreaking innovation appropriate in all settings.'; $correct[$i] = $answer[$i][1]; $explanation[$i] = ''; $i++; 

代碼“中斷”了“ 線。

比較代碼在這里:

 //Find incorrect answers and print them out with correct answers formatted for the browser. for($i=1; $i<=$totalquest; $i++){ if($_POST[$i]!=$correct[$i]){ $WrongAnswers .= "<b>You answered Question $i incorrectly:</b><br>$question[$i]<br>You answered: $_POST[$i]<br>The correct answer is: $correct[$i]<p>"; $score=$score-1; } } echo $WrongAnswers; 

和創建測試的代碼在這里:

 for($i=1; $i<=$totalquest; $i++) { echo $i.'. '.$question[$i]."<br>"; $totalans=count($answer[$i]); for($j=1; $j<=$totalans; $j++) { echo '<input type="radio" name="'.$i.'" value="'.$answer[$i][$j].'" required>'.$answer[$i][$j].'<br>'; } echo '<p>'; } 

您引用的特定問題與字符的HTML字符編碼有關。

例如您&ldquo; 為便於比較,應將其替換為易於理解的字符。 為此,您可以html_entity_decode()字符串,如下所示:

$var = "Always-unless... actually, there is no &ldquo;unless&rdquo;";
$string = html_entity_decode($var, ENT_QUOTES);

通過POST ed變量發送的字符串數據(應為表單數據)默認情況下不是經過html編碼的,因此您需要比較字符串進行解碼 提交的值進行 html 編碼

此外,字符集可能存在其他問題,您需要將其添加到表單中:

 <head>
 <meta charset="UTF-8"> /* HTML-5 */
 </head>
 <body>
 <form ... accept-charset='UTF-8'>
 ...

還要研究PHP mb_string這樣您通常可以得出如下結果:

PHP頁面(在這種情況下,接收表單數據):

 mb_internal_encoding('UTF-8');
 mb_http_output('UTF-8');
 mb_http_input('UTF-8');

  ...

 $string = html_entity_decode($var, ENT_QUOTES, "UTF-8");
 /*** 
  Or alternatively you encode the $_POSTed value.
  ***/

 if($_POST['radiochoice'] == $string){
       //... correct.
 }

從邏輯角度來看,更好的是根本不需要在頁面之間來回傳遞整個文本值,而僅僅是引用,單選按鈕value=""是傳遞到下一頁的值,因此您可以簡單地將此值設置為唯一屬性,例如數字,然后簡單地檢查一下:

  if((int)$_POST['radiochoice']) == 4){
     //open 4 picked, this is correct!
  }

從他們的角度看,用戶仍然會在頁面上閱讀相同的文本。

(int)用於強制輸入為整數,以最小化並防止CSRF和其他安全難題(這只是形式安全的更廣泛主題的一個補充)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM