Validating data = Determine if the data is in proper form.
Sanitizing data = Remove any illegal character from the data.
PHP filters are used to validate and sanitize external input.
The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker.
The filter_list() function can be used to list what the PHP filter extension offers:
Many web applications receive external input. External input/data can be:
|You should always validate external data!
Invalid submitted data can lead to security problems and break your webpage!
By using PHP filters you can be sure your application gets the correct input!
The filter_var() function both validate and sanitize data.
The filter_var() function filters a single variable with a specified filter. It takes two pieces of data:
The following example uses the filter_var() function to remove all HTML tags from a string:
The following example uses the filter_var() function to check if the variable $int is an integer. If $int is an integer, the output of the code above will be: "Integer is valid". If $int is not an integer, the output will be: "Integer is not valid":
In the example above, if $int was set to 0, the function above will return "Integer is not valid". To solve this problem, use the code below:
The following example uses the filter_var() function to check if the variable $ip is a valid IP address:
The following example uses the filter_var() function to first remove all illegal characters from the $email variable, then check if it is a valid email address:
The following example uses the filter_var() function to first remove all illegal characters from a URL, then check if $url is a valid URL:
For a complete reference of all filter functions, go to our complete PHP Filter Reference. Check each filter to see what options and flags are available.
The reference contains a brief description, and examples of use, for each function!