·  PHP – Web Forms – Server side validation

 

- Info:

  - This tutorial shows how to validate data entered through HTML form on a server side in PHP script.

 

- Example:

  - Following script displays simple HTML Form with name and age input fields.

  - Once you press submit button script calls itself and checks if age only containg digits and no letters.

  - If all is well PHP part of scrippt displays entered name and age.

  - Create PHP Web Application Test.php.

      

    Test.php

    <!-- DISPLAY FORM ------->

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="post"> <!-- action="Test.php" -->

      Name: <input type="text"   name="name"   /> <br>

      Age:  <input type="text"   name="age"    /> <br>

            <input type="submit" name="submit" />

    </form>

    

    <!-- DISPLAY FORM DATA -->

    <?php

 

      if (isset($_POST['submit']))  {

        $name = htmlentities($_POST['name']);

        $age  = htmlentities($_POST['age' ]);

        if   (validateAge($age)) { echo($name . " is " . $age . " years old."); }

        else                     { echo("Invalid age format"); }

      }

      

      function validateAge($age) {

       if   (eregi("[^0-9]", $age)) { return false; } //If non digit is found.

        else                         { return true;  }

      }

    

    ?>