Skip to content
Advertisement

POST variable verification

I want to build a simple discount system. My idea is something like this: user will enter code & I want to verify it with PHP & update the price on the invoice (can do this part, that’s why i share just this part of code)

I would like to see your solution because as of now, this isn’t working at all, no response.

my actual code (HTML form):

      <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 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"]);
        }
     }
     
     function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
        
        if ($code == "FIVE" ) {
           $codeErr = "OK";
        }else {
           $codeErr = "wrong code";
        }
     }
     
  ?>

Advertisement

Answer

This part of the code seems like it should not be placed in the test_input function, as that function returns the $data and this part is never called.

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

The following code should work as required (not tested):

<?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;
     }
     
  ?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement