karlakmkj

Basic sanitization with filter_var()

Sep 20th, 2021
1,480
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. // variables to represent different message generated depending on user input submission
  3. $validation_error = ""; //the inner HTML of our error <span>.
  4. $user_answer = "";  // assigned to the value attribute of the "answer" input element
  5. $submission_response = "";
  6.  
  7. // Write Function here
  8. if ($_SERVER["REQUEST_METHOD"] === "POST") {
  9.   $user_answer = filter_var($_POST["answer"], FILTER_SANITIZE_NUMBER_INT); // inbuilt sanitization filter to sanitize integers. First argument - variable, second argument - takes an ID representing the type of filtering that should be performed.
  10.   if ($user_answer != "-5"){
  11.     $validation_error = "* Wrong answer. Try again.";
  12.   } else {
  13.     $submission_response = "Correct!";
  14.   }
  15. }
  16. ?>
  17.  
  18. <h2>Time for a math quiz!</h2>
  19. <form method="post" action="">
  20. <h4>Question 1:</h4>  
  21. <p>What is 6 - 11?</p>
  22. <input type="text" name="answer" id="answer" value="<?= $user_answer;?>">
  23. <br>
  24. <span class="error" id="error"><?= $validation_error;?></span> <!--if wrong, message to print will be here -->
  25. <br>
  26. <input type="submit" value="Submit Your Answer">
  27. </form>
  28. <div>
  29.   <p id="answer-display">Your answer was: <?= $user_answer;?></p>
  30.   <p id="submission-response"><?= $submission_response;?></p> <!-- print message when it's correct answer-->
  31. </div>
RAW Paste Data