2013-05-19 51 views
-1

我有這樣的PHP代碼的用戶輸入。

<?php 
    $score11 = $_POST['passmarks12']; 

    if($_POST['passmarks12'] > 100){ 
     $grade11 = ""; 
    } 
    elseif ($_POST['passmarks12'] < 45){ 
     $grade11 = "Fail"; 
    } 
    $strg = " $grade11"; 

    echo $strg; 

?> 

的代碼總是打印「失敗」不管是什麼在發送

我想它,以便如果它傳入空白或無效輸入它失敗。

我應該如何正確清理輸入?

+1

如果你不能信任的投入是有效的,你檢查他們_before_做別的事情。 –

回答

-1

這PHP代碼將確保$_POST不是空的比較它與100

<?php 
    $score11 = $_POST['passmarks12']; 

    if(empty($_POST['passmarks12']) || $_POST['passmarks12'] > 100) 
     $grade11 = ""; 

    elseif ($_POST['passmarks12'] < 45) 
     $grade11 = "Fail"; 

    $strg = " $grade11" ; 

    echo $strg; 

?> 
+0

謝謝你現在工作完美 – user2260431

0

我想你想

elseif ($_POST['passmarks12'] < 45 && !empty($_POST['passmarks12'])) 
+1

這些應該是另一種方式,否則如果沒有設置$ _POST ['passmarks12']',則會出現錯誤。 – rpkamp

1

嘗試此之前:

<?php 

    //$_POST['passmarks12'] = ''; 

    if(empty($_POST['passmarks12']) || $_POST['passmarks12'] > 100) 
    { 
     $grade11 = ""; 
    } 

    else if ($_POST['passmarks12'] < 45){ 

     $grade11 = "Fail"; 
    } else{ 
      $grade11 = "Pass"; 
    } 
    $strg = " $grade11" ; 

    echo $strg; 

    ?> 
1

點:

  1. 使用isset檢查$_POST['key']是否存在。
  2. 檢查$_POST['key']是否有有效的數據類型,字符串
    它可能是array
  3. 檢查$_POST['key']是否有有效的數字格式。
  4. 比較$_POST['key'](字符串)45(整數),使用intval

例子:

<?php 

switch (true) { 

    case !isset($_POST['passmarks12']): 
    case !is_string($score = $_POST['passmarks12']): 
    case !is_numeric($score): 
     $result = 'Error (Invalid parameter)'; 
     break; 
    case (intval($score) < 45): 
     $result = 'Fail (Less than 45)'; 
     break; 
    default: 
     $result = 'Success (No less than 45)'; 

} 

echo $result;