Easy Form Validation in PHP
|We already discussed HTML5 forms of input types. The basic goal of this post is to create a form and do form validation in php using from inputs.
Post Contents
Introduction
We will create a form using bootstrap and will validate the form input types using PHP.
We can also use JavaScript for front end validation but we should always be prepared for any security attack so server-side form validation in php or any other programming language is also required.
Let’s create a form first, as we are using bootstrap forms so let’s add bootstrap libraries first.
Bootstrap Library
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
After adding bootstrap libraries, let’s put together a basic form that will have below fields.
- First Name
- Last Name
- Gender
- Subject
Form HTML
<div class="container">
<form method="POST" action="">
<div class="form-group row">
<label for="firstName" class="col-sm-2 col-form-label">First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="First Name" value="">
</div>
</div>
<div class="form-group row">
<label for="lastName" class="col-sm-2 col-form-label">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastName" name="lastName" placeholder="Last Name" value=""">
</div>
</div>
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" name="email" placeholder="Email" value="">
</div>
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-2 pt-0">Gender</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" id="gender1" value="M">
<label class="form-check-label" for="gender1">
Male
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" id="gender2" value="F">
<label class="form-check-label" for="gender2">
Female
</label>
</div>
</div>
</div>
</fieldset>
<div class="form-group row">
<label for="subject" class="col-sm-2 col-form-label">Favourite Subjest</label>
<div class="col-sm-10">
<select class="form-control" name="subject" id="subject">
<option value=''>-Select-</option>
<option value='Math'>Math</option>
<option value='English'>English</option>
<option value='Science'>Science</option>
<option value='Hindi'>Hindi</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
</div>
</form>
</div>
Our bootstrap HTML 5 form will be look like
So, we have form ready now. Lets add some server side form validation.
Form Attributes
The form needs two main attributes for work method and action. Let’s add this two attribute in the form.
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
So, we have added method as POST and action as $_SERVER[“PHP_SELF”].
The action represents, where the from content will send on form submit. In this case, we have defined $_SERVER[“PHP_SELF”], it means form data will be processed on the same page.
You must wondering , why we have added htmlspecialchars().
htmlspecialchars()
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like & (ampersand) with &
This also prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms. So, this is the first step to make code secure and prevent against any vulnerability.
Form Processing
Now we have HTML form ready with form action and method. Now, we will validate if the form is submitted blank or with values.
This is required to prevent unnecessary form submissions and identify what need to processed.
Always at the start of PHP script check whether the form has been submited ot not using $_SERVER[“REQUEST_METHOD”]. Here we are using the REQUEST_METHOD POST then we can check as below
if ($_SERVER["REQUEST_METHOD"] == "POST") {
}
Now, we will validate all required filed in PHP. Place the below code on top of your PHP script.
Form Validation in PHP Code
// define variables and initialize with empty values
$firstNameErr = $lastNameErr = $emailErr = $subjectErr = $genderErr = "";
$firstName = $lastName = $email = $gender = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = true;
if (empty($_POST["firstName"])) {
$firstNameErr = "First Name is missing";
$valid = false;
}
else {
$firstName = validate($_POST["firstName"]);
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last Name is missing";
$valid = false;
}
else {
$lastName = validate($_POST["lastName"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is missing";
$valid = false;
}
else {
$email = validate($_POST["email"]);
}
if (empty($_POST["subject"])) {
$subjectErr = "You must select 1 subject";
$valid = false;
}
else {
$subject = validate($_POST["subject"]);
}
if (empty($_POST["gender"])) {
$genderErr = "You must select gender";
$valid = false;
}
else {
$gender = validate($_POST["gender"]);
}
Above, we have defined the variable for error and fields POST values that we will be using in the validation process and in assigning form POST values.
First, we are checking, using PHP empty function that the POST field has some values or not, if found empty we are assigning some errors messages to the error variables.
And in else condition, we are storing POST values in other variables that we defined earlier.
So, in HTML we can show error messages like below .
<div class="col-sm-10">
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="First Name">
<span class="error"><?php echo $firstNameErr;?></span>
</div>
We have added a span just below the input type to show error message on the user.
We can also add input field value to the input box.
<div class="col-sm-10">
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="First Name" value="<?php echo htmlspecialchars($firstName);?>"><span class="error"><?php echo $firstNameErr;?></span>
</div>
Let’s see, how we will handle the radio button in the form during server-side validation.
<div class="row">
<legend class="col-form-label col-sm-2 pt-0">Gender</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" id="gender1" value="M" <?php if (isset($gender) && $gender == "M") echo "checked"; ?>>
<label class="form-check-label" for="gender1">
Male
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" id="gender2" value="F" <?php if (isset($gender) && $gender == "F") echo "checked"; ?>>
<label class="form-check-label" for="gender2">
Female
</label>
</div>
</div>
<span class="error"><?php echo $genderErr;?></span>
</div>
We are validation the gender field and also remembering which radio button is checked on form submit.
We should also validate form fields to prevent any vulnerability. Like, we are validating every POST field to validation function to prevent any SQL injection, XSS attacks and any other vulnerability
function validate($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
We will discuss in details in next post, how we can make our forms more secure.
Summary
So, we have done form validation in PHP. If you prefer front end validation then you should also do server-side validation because sometimes, users blocked JavaScript on their browsers so front end validation doesn’t work.
Please write in comments for any suggestion or help.
Stunning work, thank you so much for taking the time to share!