PHP Form Validation

In a Web-Application or Web page the developer or programmer would also need to validate the data in farm fields provided by the users. We are going to see how to  implement some basic security feature like sanitization and validation of the user's input so that user can not insert potentially harmful data that compromise the website security or might break the application.

Now lets see the below html form field :

form.php
<html>
<body>

  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    Name : <input type="text" name="name"/><br/><br/>
    Age : <input type="text" name="age"/><br/><br/>
    Gender :
    <input type="radio" name="gender" value="female">Female
    <input type="radio" name="gender" value="male">Male
    <input type="radio" name="gender" value="other">Other<br/><br/>
    Email : <input type="text" name="email"/><br/><br/>
    Website : <input type="text" name="website"/><br/><br/>
    Comment : <textarea name="comment" rows="6" cols="30"></textarea><br/><br/> 
    <input type="submit" name="submit" value="Submit"/>
  </form>

<?php

// php code to display the values

  if($_SERVER["REQUEST_METHOD"] == "POST") {
    echo "Name : " . $_POST['name'] . "<br/>";
    echo "Age : " . $_POST['age'] . "<br/>";
    echo "Gender : " . $_POST['gender'] . "<br/>";
    echo "Email : " . $_POST['email'] . "<br/>";
    echo "Website : " . $_POST['website'] . "<br/>";
    echo "Comment : " . $_POST['comment'] . "<br/>";
  }

?>

</body>
</html>
Output :


The Above php code does not have any validation check, ity just prints the user given data on the page when the user clicks on submit button.


The above code the we are using if() condition :
if($_SERVER["REQUEST_METHOD"] == "POST") {
  echo "Name : " . $_POST['name'] . "<br/>";
  echo "Age : " . $_POST['age'] . "<br/>";
  echo "Gender : " . $_POST['gender'] . "<br/>";
  echo "Email : " . $_POST['email'] . "<br/>";
  echo "Website : " . $_POST['website'] . "<br/>";
  echo "Comment : " . $_POST['comment'] . "<br/>";
}
Where if the REQUEST_METHOD is POST then the code will execute, either its not. Also note that in the html form we use the below php code in the action attribute.
 <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
The above php code just echo the value of $_SERVER["PHP_SELF"], which is parsed with htmlspecialchars() function. At here the $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script. So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.

The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or JavaScript code in forms.

Now in validation checking, first we need to check that the input fields are filled or empty. We can do this by below php code.
<html>
<head>
       
  <style>
    .err {color: #FF0000;}
  </style>

</head>
<body>

<?php

  // defining variables and set empty values
  $nameErr = $ageErr = $genderErr = $emailErr = $websiteErr = $commentErr = "";
  $name = $age = $gender = $email = $website = $comment = "";

  //  code to check fieled values
  if($_SERVER["REQUEST_METHOD"] == "POST") {

    if(empty($_POST["name"])) {
      $nameErr = "Name is required.";
    } else {
      $name = $_POST["name"];
    }

    if(empty($_POST["age"])) {
      $ageErr = "Age is required.";
    } else {
      $age = $_POST["age"];
    }

    if(empty($_POST["gender"])) {
      $genderErr = "Gender is required.";
    } else {
      $gender = $_POST["gender"];
    }

    if(empty($_POST["email"])) {
      $emailErr = "Email is required.";
    } else {
      $email = $_POST["email"];
    }

    if(empty($_POST["website"])) {
      $websiteErr = "Website is required.";
    } else {
      $website = $_POST["website"];
    }

    if(empty($_POST["comment"])) {
      $commentErr = "Email is required.";
    } else {
      $comment = $_POST["comment"];
    }
  }

?>

  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    Name : <input type="text" name="name"/>
    <span class="err"><?php echo $nameErr; ?></span><br/><br/>
    Age : <input type="text" name="age"/>
    <span class="err"><?php echo $ageErr; ?></span><br/><br/>
    Gender :
    <input type="radio" name="gender" value="female">Female
    <input type="radio" name="gender" value="male">Male
    <input type="radio" name="gender" value="other">Other
    <span class="err"><?php echo $genderErr; ?></span><br/><br/>
    Email : <input type="text" name="email"/>
    <span class="err"><?php echo $emailErr; ?></span><br/><br/>
    Website : <input type="text" name="website"/>
    <span class="err"><?php echo $websiteErr; ?></span><br/><br/>
    Comment : <textarea name="comment" rows="6" cols="30"></textarea>
    <span class="err"><?php echo $commentErr; ?></span><br/><br/>
    <input type="submit" name="submit" value="Submit"/>
  </form>

<?php

// php code to display the values

  if($_SERVER["REQUEST_METHOD"] == "POST") {
    echo "Name : " . $_POST['name'] . "<br/>";
    echo "Age : " . $_POST['age'] . "<br/>";
    echo "Gender : " . $_POST['gender'] . "<br/>";
    echo "Email : " . $_POST['email'] . "<br/>";
    echo "Website : " . $_POST['website'] . "<br/>";
    echo "Comment : " . $_POST['comment'] . "<br/>";
  }

?>

</body>
</html>
Output :


The above code will check the form field data and then if the form field values arfe empty then it sets the error message or sets the values. The empty() function is used to check the form data. For example :
 empty($_POST["field_name"]);
If the data field is empty then it returns false, otherwise true.

Validating data with PHP functions :

There are some special functions available in PHP, which the help of them we can validate or parse the user supplied data. These functions are :
  • trim() : The trim() function will stripout unnecessary characters like extra space, tab, newline etc from the user input data. 
  • stripslashes() : The stripslashes() function remove backslashes (\) from the user input data.
  • htmlspecialchars() : The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or JavaScript code in forms.
We can use all tree above given function in a user defined function like :
function validate_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
Now we can use the above function in our form page.
<html>
<head>
       
  <style>
    .err {color: #FF0000;}
  </style>

</head>
<body>

<?php

  // function to validate input data
  function validate_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
  }

  // defining variables and set empty values
  $nameErr = $ageErr = $genderErr = $emailErr = $websiteErr = $commentErr = "";
  $name = $age = $gender = $email = $website = $comment = "";

  //  code to check fieled values
  if($_SERVER["REQUEST_METHOD"] == "POST") {

    if(empty($_POST["name"])) {
      $nameErr = "Name is required.";
    } else {
      $name = validate_input($_POST["name"]);
    }

    if(empty($_POST["age"])) {
      $ageErr = "Age is required.";
    } else {
      $age = validate_input($_POST["age"]);
    }

    if(empty($_POST["gender"])) {
      $genderErr = "Gender is required.";
    } else {
      $gender = validate_input($_POST["gender"]);
    }

    if(empty($_POST["email"])) {
      $emailErr = "Email is required.";
    } else {
      $email = validate_input($_POST["email"]);
    }

    if(empty($_POST["website"])) {
      $websiteErr = "Website is required.";
    } else {
      $website = validate_input($_POST["website"]);
    }

    if(empty($_POST["comment"])) {
      $commentErr = "Email is required.";
    } else {
      $comment = validate_input($_POST["comment"]);
    }

  }

?>

  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    Name : <input type="text" name="name"/>
    <span class="err"><?php echo $nameErr; ?></span><br/><br/>
    Age : <input type="text" name="age"/>
    <span class="err"><?php echo $ageErr; ?></span><br/><br/>
    Gender :
    <input type="radio" name="gender" value="female">Female
    <input type="radio" name="gender" value="male">Male
    <input type="radio" name="gender" value="other">Other
    <span class="err"><?php echo $genderErr; ?></span><br/><br/>
    Email : <input type="text" name="email"/>
    <span class="err"><?php echo $emailErr; ?></span><br/><br/>
    Website : <input type="text" name="website"/>
    <span class="err"><?php echo $websiteErr; ?></span><br/><br/>
    Comment : <textarea name="comment" rows="6" cols="30"></textarea>
    <span class="err"><?php echo $commentErr; ?></span><br/><br/>
    <input type="submit" name="submit" value="Submit"/>
  </form>

<?php

  // php code to display the values

  if($_SERVER["REQUEST_METHOD"] == "POST") {
    echo "Name : " . $_POST['name'] . "<br/>";
    echo "Age : " . $_POST['age'] . "<br/>";
    echo "Gender : " . $_POST['gender'] . "<br/>";
    echo "Email : " . $_POST['email'] . "<br/>";
    echo "Website : " . $_POST['website'] . "<br/>";
    echo "Comment : " . $_POST['comment'] . "<br/>";
  }

?>

</body>
</html>
Output :




Next Topic :