POST 变量验证

POST variable verification

我想建立一个简单的折扣系统。 我的想法是这样的:用户将输入代码 & 我想用 PHP 验证它并更新发票上的价格(可以做这部分,这就是为什么我只分享这部分代码)

我想看看你的解决方案,因为到目前为止,这根本不起作用,没有任何反应。

我的实际代码(HTML 形式):

      <form method = "post" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
     <table>
        <tr>
           <td>code:</td>
           <td><input type = "text" name = "code">
           <span class = "error"><?php echo $codeErr;?></span>
           </td>
        </tr>
            
        <td>
           <input type = "submit" name = "submit" value = "Submit"> 
        </td>
            
     </table>
        
  </form>

PHP代码:

      <?php
  
  
  $codeErr = "";
  $code = "";
     
     if ($_SERVER["REQUEST_METHOD"] == "POST") {
         
         
         
         
        if (empty($_POST["code"])) {
           $codeErr = "Code can not be blank.";
        }else {
           $code = test_input($_POST["code"]);
        }
     }
     
     function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
        
        if ($code == "FIVE" ) {
           $codeErr = "OK";
        }else {
           $codeErr = "wrong code";
        }
     }
     
  ?>

这部分代码似乎不应该放在 test_input 函数中,因为那个函数 returns $data 并且这部分永远不会被调用。

if ($code == "FIVE" ) {
   $codeErr = "OK";
}else {
   $codeErr = "wrong code";
}

以下代码应按要求工作(未测试):

<?php
  
  
    $codeErr = "";
    $code = "";
     
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
         
        if (empty($_POST["code"])) {
           $codeErr = "Code can not be blank.";
        }else {
           $code = test_input($_POST["code"]);
        
           if ($code == "FIVE" ) {
              $codeErr = "OK";
           }else {
              $codeErr = "wrong code";
           }
        }
     }
     
     function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
     }
     
  ?>