karlakmkj

Using Options with filter_var()

Sep 21st, 2021
748
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. $message = "";
  3. $month_error = "";
  4. $day_error = "";
  5. $year_error = "";
  6.  
  7. // Create variables for range of options
  8. $month_options = ["options" => ["min_range" => 1, "max_range" => 12]];
  9. $day_options = ["options" => ["min_range" => 1, "max_range" => 31]];
  10. $year_options = ["options" => ["min_range" => 1903, "max_range" => 2021]];
  11.  
  12.  
  13. // create function to validate user input based on each input option range
  14. function validateInput($type, &$error, $options_arr){
  15.   if (!filter_var($_POST[$type], FILTER_VALIDATE_INT, $options_arr)){
  16.     $error = "* Invalid ${type}";
  17.     return FALSE;
  18.   } else {
  19.     return TRUE;
  20.   }
  21. }
  22.  
  23.   if ($_SERVER["REQUEST_METHOD"] == "POST") {
  24.     $test_month = validateInput("month", $month_error, $month_options);
  25.     $test_day = validateInput("day", $day_error, $day_options);
  26.     $test_year = validateInput("year", $year_error, $year_options);    
  27.     if ($test_month && $test_day && $test_year){
  28.       $message = "Your birthday is: {$_POST["month"]}/{$_POST["day"]}/{$_POST["year"]}";
  29.     }  
  30.   }
  31.  
  32. ?>
  33.  
  34. <form method="post" action="">
  35.     Enter your birthday:
  36.     <br>
  37.     Month: <input type="number" name="month" value="<?= $_POST["month"];?>">
  38.     <span class="error"><?= $month_error;?>     </span>
  39.   <br>
  40.     Day: <input type="number" name="day" value="<?= $_POST["day"];?>">
  41.   <span class="error"><?= $day_error;?>     </span>
  42.     <br>  
  43.     Year: <input type="number" name="year" value="<?= $_POST["year"];?>">  
  44.     <span class="error"><?= $year_error;?>      </span>
  45.     <br>
  46.     <input type="submit" value="Submit">
  47. </form>
  48.     <p><?= $message;?></p>
RAW Paste Data