Form Validation – Server Side

Oh! What would we do without web forms? No tweeting, a blank Facebook status update, a blank CV on your LinkedIn profile, or the inability to purchase online that expensive smart phone you have been saving for.

Web forms are an integral part of websites; they allow us to interact with different web systems. We use them everyday for various stuff e.g. business transactions, social interactions. And of course they are vulnerable to various risks such as hacking, wrong information storage or no information at all.

In this article and the next one we will look at form validation. Validation of forms is done to ensure that the correct data has been inserted into the form or required data is not missing from a form input such as the text field. Forms inputs are created using HTML and they are of various types:

  • Text field
  • Text area
  • Radio buttons
  • Select list
  • Check box
  • Submit button

Forms can be validated on the client side or the server side. The client side validation means the form is validated on the web browser before the data is submitted to a web server while in server side validation the form data is submitted to the web server first and validated there. If all is not ok, the server responds with a negative feedback hence prompting the form’s user to insert data again.

In this post we’ll focus on server side form validation; I don’t want to bore you with a very long tutorial 🙂

At the same time we’ll look at sanitizing form data i.e. making sure that any data input by a user is void of characters that may be malicious to the database or the user. User form input can be laced with malicious code (Javascript code) that a hacker can utilize to either insert bad data or redirect a user to another malicious harmful  file.

Server Side Validation

We’ll create a simple form for sending a user’s name, email address and phone number as shown in the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Form Test </title>
</head>
<body>
	<form name="user-form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
		<label>Name</label>
		<input type="text" id="user-name" name="name">

		<label>Email</label>
		<input type="email" id="user-email" name="email">

		<label>Phone No.</label>
		<input type="text" id="user-phone" name="phone">

		<input type="submit" value="Send" name="user-form-btn" id="user-form-btn">
	</form>
</body>
</html>

You will notice that the action attribute for the form has a strange value. We’ll insert the PHP code that will process the form’s data in the same file as the form. The PHP code will be above the HTML code and in the action attribute we will use:

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

I will explain later in the article what the above code snippet means. The PHP code should be as follows:

<?php
// define variables and initialize with empty values
$nameError = $emailError = $phoneError = "";
$userName = $userEmail = $userPhone = "";
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["user-name"])) {
        $nameErr = "Missing";
    }
    else {
        $name = $_POST["user-name"];
    }
 
    if (empty($_POST["user-email"])) {
        $addrErr = "Missing";
    }
    else {
        $address = $_POST["user-email"];
    }
 
    if (empty($_POST["user-email"]))  {
        $emailErr = "Missing";
    }
    else {
        $email = $_POST["user-email"];
    }
}
// Beginning of HTML code
?>

PHP Code Demystified

  1. The variables are initially set to empty.
  2. Using an IF statement, we check whether the form has been submitted by the request type. In this case it’s the POST request method.
  3. The empty() function checks if the fields are empty i.e. do not have any data. Does the form have values you can use? If they are empty an error message is displayed using the error variables, otherwise the form data is collected and stored in the variables like the $userName variable.

What is $_SERVER[“PHP_SELF”]?

Since we are submitting data to the page itself, we’ll use the $_SERVER[“PHP_SELF”] super global variable. Remember the PHP code for processing the form data is on the same page as the HTML form.

However, $_SERVER[“PHP_SELF”] can be exploited by hackers to insert malicious code in process called XSS (Cross Site Scripting). To protect our form we make use of the htmlspecialcharacters() function. This is used here to change specific HTML characters to their HTML entity names. For example < and > HTML characters are &lt and &gt entity names respectively. The use of htmlspecialcharacters() is a way of form sanitization.

To further the sanitization process, we can strip off unnecessary characters such as extra space (very common with users) and remove back slashes using the trim() and the stripslashes() functions respectively. These two can be combined with the htmlspecialcharacters() into one function to make our code look more clean. So no need of using htmlspecialcharacters() in the form’s action attribute:

<?php
// define variables and initialize with empty values
$nameError = $emailError = $phoneError = "";
$userName = $userEmail = $userPhone = "";
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["user-name"])) {
        $nameErr = "Missing";
    }
    else {
        $name = input_data($_POST["user-name"]);
    }
 
    if (empty($_POST["user-email"])) {
        $addrErr = "Missing";
    }
    else {
        $address = input_data($_POST["user-email"]);
    }
 
    if (empty($_POST["user-email"]))  {
        $emailErr = "Missing";
    }
    else {
        $email = input_data($_POST["user-email"]);
    }
}
function input_data($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
// Beginning of HTML code

?>

Ensure you follow the proper order of sanitizing form data (trim -> remove slashes -> change html special characters) as shown in the code above.

Hence our form is now secure from villains 🙂

A Better and New Way of Sanitizing Form Data

We can do by  using the filter extension of the most recent PHP version. For example:

$user_name = filter_input(INPUT_POST, ‘user_name’, FILTER_SANITIZE_STRING);

There are various types of sanitizing filters. Check them out here on the official documentation  of PHP.

Finishing

The error message placeholders can now be inserted into the HTML form so that when the validation is negative, an error message is displayed. For example:

can be placed right below the name text field input. We can then style the message, maybe with a block that has a light red background, has padding and is rounded. For example:

Error

.error {
  display:block;
  color: #a94442;
  background-color: #f2dede;
  border-color: #ebccd1;
  padding:15px;
  border-radius:5px;
}

So now our form is complete. You can access the full code (gist), two versions, from my github library as shown below; there are two versions since we have approached two ways of sanitizing the form i.e. using htmlspecialcharacters() differently. On a different note, here’s how you can insert gist in a WordPress post from from a Github repo.

Version One:

Version Two:

In the next article we will look at validating the form from the client side. The client side will be divided into two part: Javascript and HTML5.

Further Reading

February 7, 2015

Posted In: Information Technology

Tags: ,

Leave a Comment