Php Form Validation: Comprehensive Guide

PHP Form validation is an important aspect that ensures user-submitted data is accurate, complete, and secure. In this chapters, we will show you how to validate form data through PHP.



PHP Form Validation

These pages will show you how to process PHP forms while keeping security in mind. To protect your form from hackers and spammers, it is important that form data be validated properly.

When processing forms, think SECURITY!

Here are some of the input fields we will be working in these chapters.

This form needs to be validated according to the following rules:


Here are the validation rules that need to be followed for the form above:

FieldsValidation Rules
First name:Required field + There must only be letters and whitespace in the text
Last name:Required field + There must only be letters and whitespace in the text
Age:Required field + Valid number greater than 0
EmailRequired field + The email address must contain an (@ and .)
Year of Experience:Optional field + If you have experience, enter a number more than 0
Designation:Required field + There must only be letters and whitespace in the text
LinkedInOptional field + If have account on linkedIn then enter it
Write your Skills:Required field + There must only be letters and whitespace in the text

Text Fields

Among the different fields available to you, you will find a text input element for first name, last name, age, email, designation, and linkedin, and a text area for the write your skills.

As you can see from the HTML code, it looks like this:

First name: <input type="text" name="firstname">
Last name: <input type="text" name="lastname">
Age: <input type="text" name="age">
E-mail: <input type="text" name="email">
Designation: <input type="text" name="designation">
LinkedIn: <input type="text" name="linkedin">
Write your Skills: <textarea name="skills" rows="5" cols="40"></textarea>

Select Button

The year of experience fields are select option buttons and the HTML code looks like this:

<label for="yrofexp">Year of Experience:</label>
<select name="yrofexp" id="yrofexp">
<option value="">Select number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>

The Form Element

Here is the HTML code for the form that looks like this:

<form method=”post” action=”<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>”>

What is the meaning of the variable $_SERVER[“PHP_SELF”]?

‘$_SERVER[“PHP_SELF”]’ is a super global variable that returns the name of the file that has been executing the script in the current moment.

This means that $_SERVER[“PHP_SELF”] sends the submitted form data to the page itself, rather than jumping to another page to fetch it.

By doing this, you will be able to display error messages on the same page that the form is displayed on.

How does the htmlspecialchars() function work?

A special character can be converted into an HTML entity using the htmlspecialchars() function.
This means HTML characters like < and > will be replaced with &lt; and &gt; as a result.
The advantage of this is that hackers are not able to exploit the code by injecting HTML or Javascript code into it (cross-site scripting attacks).


Big Note on PHP Form Security

Hackers can use the $_SERVER[“PHP_SELF”] variable to gain access to your server!

A website’s PHP_SELF can be exploited by allowing a user to enter a slash (/) at the front of the page, and the browser will execute some Cross Site Scripting (XSS) commands.

Cross-site scripting (XSS) is a security vulnerability that can affect web applications, including those built with PHP. While there have been various improvements in PHP versions to address XSS, it is not accurate to say that any specific version of PHP is “secure” against all forms of XSS attacks.

Attackers can take advantage of XSS by injecting client-side scripts into a user’s Web page at the time the Web page is being viewed.

Let us suppose that we have the form on a page named form.php:

<form method=”post” action=”<?php echo $_SERVER[“PHP_SELF”];?>”>

A user would enter the normal URL in the address bar such as “http://www.mrexample.com/form.php” which would translate to the following:

<form method=”post” action=”form.php”>

It has gone well so far.

Suppose a user enters the following URL into the address bar of the browser:

http://www.mrexample.com/form.php/%78%2A%3Cscript%3Ealert(‘PageHacked’)%3C/script%3E

This will result in the following code being translated into the following:

<form method=”post” action=”form.php/”><script>alert(‘PageHacked’)</script>

An alert command is added to the script tag by this code. As soon as the page loads, the JavaScript code will be executed by the browser (an alert box will be displayed to the user).

In this example, we showed how the PHP_SELF variable can be exploited in a simple and harmless manner.

In order to prevent malicious code on a system, users need to always be aware that hackers can redirect a user’s file to a different server, change a global variable, or submit a form to another address to steal personal information.


How To Avoid $_SERVER[“PHP_SELF”] Exploits?

The htmlspecialchars() function can be used to avoid exploits associated with $_SERVER[“PHP_SELF”].

This is what the form code should look like:

<form method=”post” action=”<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>”>

This function converts special characters into HTML entities using the htmlspecialchars() function.

Now, if the user tries to attack the PHP_SELF variable, the output that will appear will look something like this:

<form method=”post” action=”form.php/"><script>alert(‘PageHacked’)</script>”>
A successful exploit attempt was made, but no harm was found.

Validate Form Data Through PHP

We will begin by passing every variable through PHP’s htmlspecialchars() function in order to convert them into special characters.

Using the htmlspecialchars() function, let’s suppose the user tries to input the following into a text box while using the htmlspecialchars() function:

<script>location.href(‘http://www.hacked.com’)</script> – Because it is saved as HTML escaped code, the code would not be able to be executed, like this:

<script>location.href(‘http://www.hacked.com’)</script>

This code is now safe for displaying on a web page or inside an email message.

Also, as soon as the user submits the form, we will do two more things:

Use the PHP trim() function to remove unnecessary characters (extra spaces, tabs, newlines) from the input data of the user.

The PHP stripslashes() function can be used to remove backslashes () from the user input data.

The next step in the process will be to write a function that will take care of all the checking for us (which is certainly much more convenient than having to go through the same process of writing the same procedure over and over again).

Input_validation() is what we are going to call our function.

This will allow us to check each $_POST variable using the Input_validation() function, and the script will look like the following:

We would like to draw your attention to the fact that at the very beginning of the script, we use $_SERVER[“REQUEST_METHOD”] to determine whether the form has been submitted.

When the REQUEST_METHOD is POST, it should be validated.

This form will be displayed blank if it has not been submitted yet and no validation has taken place.

In the example above, however, all input fields are optional, so the user can enter whatever they want. Even if the user does not enter any data into the script, the script will still work fine.

<?php
$firstname = $lastname = $age = $email = $designation = $skills = $linkedin = $yrofexp = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$firstname = input_validation($_POST["firstname"]);
$lastname = input_validation($_POST["lastname"]);
$age = input_validation($_POST["age"]);
$email = input_validation($_POST["email"]);
$skills = input_validation($_POST["skills"]);
$designation = input_validation($_POST["designation"]);
$linkedin = input_validation($_POST["linkedin"]);
$yrofexp = input_validation($_POST["yrofexp"]);
}

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

Merge Both HTML and PHP code:

Example: 

<!DOCTYPE HTML> <html lang="en"><head> <title>PHP Form</title> </head><body><?php $firstname = $lastname = $age = $email = $designation = $skills = $linkedin = $yrofexp = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $firstname = input_validation($_POST["firstname"]); $lastname = input_validation($_POST["lastname"]); $age = input_validation($_POST["age"]); $email = input_validation($_POST["email"]); $skills = input_validation($_POST["skills"]); $designation = input_validation($_POST["designation"]); $linkedin = input_validation($_POST["linkedin"]); $yrofexp = input_validation($_POST["yrofexp"]); }function input_validation($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?><h2>PHP Form Validation</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> First name: <input type="text" name="firstname"> <br><br> Last name: <input type="text" name="lastname"> <br><br> Age: <input type="text" name="age"> <br><br> E-mail: <input type="text" name="email"> <br><br> <label for="yrofexp">Year of Experience:</label> <select name="yrofexp" id="yrofexp"> <option value="">Select number</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> </select> <br><br> Designation: <input type="text" name="designation"> <br><br> LinkedIn: <input type="text" name="linkedin"> <br><br> Write your Skills: <textarea name="skills" rows="5" cols="40"></textarea> <br> <br><br> <input type="submit" name="submit" value="Submit"></form><?php echo "<h2>Your Form Data:</h2>"; echo "First Name: ".$firstname; echo "<br>"; echo "Last Name: ".$lastname; echo "<br>"; echo "Age: ".$age; echo "<br>"; echo "Email: ".$email; echo "<br>"; echo "Year of Experience: ".$yrofexp; echo "<br>"; echo "Designation: ".$designation; echo "<br>"; echo "LinkedIn URL: ".$linkedin; echo "<br>"; echo "Skills: ".$skills;?></body></html>
Next, we need to modify the input fields to make them mandatory and create error messages if any errors occur.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

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