Form Validation in PHP

Form validation is one of the most important parts of any user based website which collects a basic info about the user. The data entered by the user through the HTML forms must be verified. This concept is known as form validation.

The data is checked for its validity using PHP scripts. The can be from text fields, radio buttons, checkboxes, number  and etc.

Look at the following example for better understanding:

<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Registration Form</h2>
<form action="form.php" method="POST"> 
First name:
<input type="text" name="firstname"><br>
 Last name:
<input type="text" name="lastname"> <br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="form_submitted" value="1"/>
<input type="submit" value="Submit">
</form>
</body>
</html>

This form takes the firstname, lastname and email as the input from the user. Now, this data must be validated. We will be using a function which will check for three things, first is to check if its empty. secondly we will remove the extra white spaces using the trim() and finally, we will  remove the stripslashes() to remove the backslashes(\) from the data.

Look a the following example which will implement the above mentioned three things:

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

A COMPLETE FORM

A complete form is that form which uses validation and checking for the data.  The usage of all the inbuilt functions like trim(), stripslashes(), preg_match(), filter_val() for the above tasks. One can refer to previous posts on form handling for the same.

Leave a Comment

Your email address will not be published. Required fields are marked *