PHP Filters to Sanitize and Validate Data : Examples

PHP Filters to Sanitize and Validate Data
This post explain the PHP filters to sanitize and validate external data with example code. PHP filter has useful extensions which used to check user input and designed in the way to make validation quite easy and faster.

In web application we commonly need to sanitize and validate user input data like email, number, string, IP address etc. By using these PHP filter extension we can easily achieve this.

Using PHP Filters:

To sanitize or validate the user data we are using PHP ‘filter_var()’ function. The syntax of this function:

filter_var(var, filtername, options)

var – it is the required variable to filter
filtername – It is optional parameter, which used to specify the ID or name of the filter.
options – Optional parameter, used to speficy option/flag for each filter type.

Validate Integer and Float Number:

The following code example validate the number, whether it is an integer or not using ‘FILTER_VALIDATE_INT‘ filter ID. To validate float number use ‘FILTER_VALIDATE_FLOAT‘ ID.

We can validate an integer number within a range. For example check whether integer number exist between 100 to 999. Syntax to get this.

filter_var($int, FILTER_VALIDATE_INT, array(“options” => array(“min_range” => 100,”max_range” => 999)))

Sanitize and Validate Email Addresses:

In this example we are using ‘FILTER_SANITIZE_EMAIL‘ filter to sanitize and ‘FILTER_VALIDATE_EMAIL‘ to validate email address.

In sanitize filtration, remove all illegal characters like {, }, (, ), // etc..

Its shown an output ‘’ is an valid email address.

Validate an IP Address:

Using ‘FILTER_VALIDATE_IP‘ filter we can check about IP address is valid or not. See below example:

It output shown as 164.12.2540.1 is not a valid IP address.

Note: You can use FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 flags to validate IPV4 or IPV6 IP addresses.

Sanitize a String Data:

Use ‘FILTER_SANITIZE_STRING‘ filter to remove all HTML element from an string.

The output shown somthing like this: “PHP Filters to Sanitize and Validate Data”.

Sanitize and Validate URLs:

FILTER_SANITIZE_URL filter removes all illegal characters from a URL except all letters, digits and $-_.+!*'(),{}|\\^~[]`”><#%;/?:@&=.

Its remove the illegal character and shows output as “”.

FILTER_VALIDATE_URL filter use to validate an URL.

Validate Boolean Value:

FILTER_VALIDATE_BOOLEAN filter used to validates value as a Boolean option. Its return TRUE for “1”, “true”, “on” and “yes” and return FALSE for “0”, “false”, “off” and “no”. Otherwise return NULL value.

It output as bool(true) value.

Sanitize Encoded Filter:

PHP FILTER_SANITIZE_ENCODED Filter encode special characters into $url variable. This filter work like urlencode() function.

Output shows something like that:

Above explained PHP filters to sanitize and validate data used it directly in your web application without any further installation.

Leave a Comment