Is PHP Form Validation Worth It?

Is PHP Form Validation Worth It?

Have you ever wondered how much PHP form validation goes into developing a web form?

PHP Form Validation code is a set of validation rules that allows you to create server-side validation to the PHP forms quickly with little efforts. Form validation is really crucial for dynamic web pages.

A volume of all the leading websites today are running on PHP. As the websites are no longer narrowed to being informational gateways and become business tools, you should go beyond standard functionalities while designing web pages. Next to the visitors and the user experience of your website, a web form validation demands more dedication as it indirectly creates a cordial relation with prospective clients. However, many of us ignore this fact. The result is complex and frustrating web forms that conceive a negative experience, malicious database manipulation, and system crash.

Thankfully, PHP form validation is not rocket science. PHP includes tons of great libraries and built-in validations. It is just a heap of the check using a generic PHP form validation script.

Generic PHP Form Validation Script

Generic PHP Form Validation script is meant to simplify the action of adding validation to your PHP forms. The only thing you need to do is associate the validation requirement of each element of your form with the available set of “validation descriptors”. The “validation descriptor” is the string stating the kind of validation to be executed. For instance, “alpha” specifies allow only alphabetic characters, and “num” meant to check numeric data. The table below lists the common generic PHP form validation descriptors: 

Validation Descriptors

Description

req

The field is mandatory

num

Checks numeric data

alnum

The field should include only alphabetic or numeric character

email

Verify for valid email ID

alpha

Check alphabetic data

lt=???

Verify the input to be less than the value passed

gt=???

Verify the input to be greater than the value passed

maxlen=???

Verify the length of input to the maximum

minlen=???

Verify the length of input to the required minimum

 

Importance of PHP Form Validation

The main goal of PHP Form Validation code is to make sure the user has provided all the necessary details and in the proper format in order to successfully proceed with the requested operation. The PHP code validates the values entered by a user into the form and if it does not match the criteria specified, they’re returned back to the form with the list of offending fields along with error messages. Invalid user input can cause unexpected errors in future processing. As such, PHP includes countless inbuilt validation functions to check user inputs. Here are some of the inbuilt PHP form validation functions:

Filters for validation

Description

FITER_VALIDATE_DOMAIN

Validates the domain name label lengths

FILTER_VALIDATE_EMAIL

Validates the e-mail address

FILTER_VALIDATE_FLOAT

Validates data as float, & translates to float on success.

FILTER_VALIDATE_INT

Validates data as integer, & translates to integer on success.

FILTER_VALIDATE_IP     

Validates data as IP address

FILTER_VALIDATE_MAC

Validates data as MAC address

FILTER_VALIDATE_REGEXP

Validates data against regexp

FILTER_VALIDATE_URL

Validates data as URL

 

Example: Form Validation with PHP

Let us take an example to construct & validate a Form using PHP and HTML. We will create a simple form using HTML and process as well as validate the content of the form with PHP form validation functions. Before constructing an HTML form, we should decide which HTTP method to use in the HTTP request. Among the multitude of HTTP request methods, programmers generally prefer to use GET and POST methods for forms. Since we are about to send sensitive data like emails with an HTTP request, we are proceeding with POST. GET method can be used when we want to retrieve data from the server. The example below illustrates the HTML script for a simple form:

PHP Form Validation - ExampleWhen the user completes the form above and clicks the submit button, the input data is sent for processing to the PHP file, “action.php” depicted below:
PHP form validation - Action.php As we can see, the PHP form validation scripts in the above example check the form inputs to avoid processing errors.

Let’s explore how an error can occur. Assume that the user has missed out any of the fields in the Form above. The PHP code validates whether all the variables are set using the empty () function. This function is meant to check whether the given arguments are empty or not. Here is the description of the function:

Empty () function

Syntax

 

empty ( $var )

Values reflect as an empty value:

 

NULL

FALSE

0 - 0 as an integer

"0" - 0 as a string

0.0 - 0 as a float

"" - an empty string

array() - an empty array

 

If email, name, phone or gender variable is not set, PHP script will raise an error “----- field is required”. If the first validation fails, then the script stops running the subsequent validation rules.

When the empty ($_POST[$key] && in_array($key, $validateArray)) is not empty, the PHP script proceeds with the further validation.

Next, we have validated the email with filter-var () function & FILTER_VALIDATE_EMAIL flag. If the email is invalid, the validation script returns false.

The last PHP Form validation in the above script is phone number validation. The script is validated with filter-var () and FILTER_VALIDATE_INT flag. This method can validate any integer key (like groupId, userId, etc.) in the timestamp, database, etc. The main advantage of this function is that it converts string numbers “15” for example to actual integers 15.

Since we have stored the error messages in session, any validation error occurs in the ation.php page will redirect the page back to the form page.ation.php

The PHP script in the form page echoes the session message as shown below and displays the error message to the user:Error Message

PHP Form Validation and Form Security Check

Most people think that both form validation and form security check are the same. However, form security is a separate process that should be handled along with PHP form validation. In addition, Form security check should be added to form validation to prevent web pages from malicious exploits. Improper validation of user input can increase the risk of security vulnerabilities. Attackers can take this opportunity and target your web page with the following attacks:

  • Header injection – involves sending email spams from your web server.
  • SQL injection – intend to corrupt your database
  • Cross-site scripting attacks - involves the posting of malicious data on your site.

Example to Prevent XSS using PHP Form Validation

Let’s take a deep look at XSS attack and how to prevent it with PHP form validation and security check. According to our above Form page, when the user enters the name, it will be saved in the database without any validation. Imagine an attacker enters the following script in the name field:

<script>location.href='https://www.xyz.com'</script> 

 

As a result, the malicious script gets stored in the database and the webpage displays the script as the name. Then, every user who visits the webpage will be redirected to the attacker’s site. This is how the hackers accomplish the Cross-site scripting attack (XSS):

With PHP, it is pretty simple to defend our web pagefrom XSS attack. Here is an example:
web pagefrom XSS attackThe htmlspecialchars() function of PHP escapes the HTML code and converts the input as shown below:

Input Processing Before Validation

<script>location.href='https://www.xyz.com'</script>

Input processing After validation

&lt;script&gt;location.href='https://www.xyz.com'&lt;/script&gt;

 

In addition, the trim () removes the extra spaces; hence, the extra spaces in the input won’t occupy space in the database.

Better safe than sorry

PHP form validations are tiny steps that can support the user to fill out the form easily and as fast as possible. In addition, they allow the necessary validation of user input without submitting anything to the database. When a user fills out a form, if it is unclear what he is doing wrong and there is no message to guide him, then he will more likely to give up and stroll away to another web site. Running validation on the form data while it is entered means user can be accurate and confident about his entry and this avoids unwanted frustrations.

Author

Talk To Our Experts