i

PHP Tutorial

PHP filter_var() Function

PHP filters are used to validate and sanitize any external input and is very useful when the data source contains any unknown data or user input. For example, data from an HTML form, cookies, web service data, sql statements results, service variables etc.

There are two types of filters in PHP

1. Validation – Validation is used to check or validate if the data meets certain requirements such as FILTER_VALIDATE_EMAIL will check for a valid email address, but it will not change the data or user input.

2. Sanitization – Sanitization will sanitize the data and it can change the data by removing any undesired characters. For example, FILTER_SANITIZE_EMAIL will remove the characters that are not correct for an email address or an email should not contain.

PHP filter extension has many functions that are required to check user input and it makes data validation easier. You can use filter_list() function to list all the filter names or id that filter extension offers.

PHP Filter_var() Function

filter_var() function is used to sanitize and validate the data and it filters a single variable with a filter specified in the function.

Syntax : filter_var(variable, filter, options);

where variable is the value to filter, filter is the ID of filter to apply, and options specifies one or more flags to be used. 

For example: filter_var(‘contact@yourphp.com’, FILTER_VALIDATE_EMAIL);

filter_var($email, FILTER_CALLBACK, array(‘options’ => ‘strtoupper’));