Validating User Input on the server-side

Allowing the user to free-form data enter is fraught with problems - if something can go wrong it will. One way to ensure they type what you want is to validate it using a filter - let's see how:


You have yet to enter a number

 

Code:

<form name="datainput" method="post" action="index.php">
<input type="text" name="data" value="type in a number 1 .. 10" />
<input type="submit" name="submit" value="go" />
</form>
<?php
 if (isset($_POST["submit"])) {
    // user HAS entered something and pressed the SUBMIT button
    $data = $_POST["data"];
    echo "<br> The entered text was '". $data ."'";
 
    $int_options = array(
      "options"=>array
      (
         "min_range"=>1,
         "max_range"=>10   //you can specify an acceptable integer range
      ));
    if(!filter_var($data, FILTER_VALIDATE_INT, $int_options)){
      // FILTER_VALIDATE_INT,  FILTER_VALIDATE_FLOAT, FILTER_VALIDATE_URL, FILTER_VALIDATE_EMAIL
      // are all built in error validation types
         echo(" which is NOT a valid integer number 1..10");
    } else {
         echo(" which is a valid integer 1..10 number");
    }
   
 } else {
      echo "<br> You have yet to enter a number"; 
 }
?>