Filter PHP variables using filter_var function

Filters in PHP are highly useful to filter and validate data coming from non reliable and insecure sources. Additionally, the PHP filter extension is designed to make data filtering easier and quicker. Almost all web applications depend on external input. Usually this comes from a user or another application (like a web service). Implementation of filters can stop the undesirable data. This external data can be in the form of cookies, web services, server variables and database query results etc. Some of the important functions in PHP which are used for this purpose would be discussed in this tutorial.

As an initial example, the filter_var() function can validate an integer. For example:

In the above example, the “FILTER_VALIDATE_INT” is used to filter the variable. Since the integer is valid, the output of the code above will be: “Integer is valid”. If we try with a variable that is not an integer (like “123abc”), the output will be: “Integer is not valid”.

For additional filtering features, options and flags can be utilized. Different filters have different options and flags. In the example below, we validate an integer using the filter_var() and the “min_range” and “max_range” options:

Options must be put in an associative array with the name “options”. If a flag is used it does not need to be in an array.

In the example below, we would validate an input coming from a form. For that, before validating the data, its existence would be confirmed. Then it would be filtered using the filter_input () function:

The above example would check if an “email” input variable of the “GET” type exist. After that, it would check if it is a valid email address.

With the utilization of filters, users can get rid of the annoying and unwanted data that keep pouring from random resources. This can also be implemented to get rid of spamming.

Looking for a quality hosting service? here are a few I suggest.
BlueHost | HostGator | Media Temple
Ali has been an entrepreneur in web, video and related technologies. Having worked with many business across the globe, Ali stands truly a great pillar in the business working with him.