PHP Filters
Validating data: It determine if the data is in proper form.
Sanitizing data: It remove any illegal character from the data.
The PHP Filter Extension
It is used to validate and sanitize external input. The filter_list() function can be used to list what the PHP filter extension offers.
Example - filter_list()
PHP filter_var() Function
filter_var(var, filtername, options)
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 variable you want to check
- The type of check to use
Sanitize a String
To remove all HTML tags from a string:
Example - sanitize a string
Validate an Integer
To check if the variable $int is an integer.
If $int is an integer, the output of the code below will be: "Integer is valid". If $int is not an integer, the output will be: "Integer is not valid":
Example - validate an integer
filter_input() Function
The filter_input() function gets the specific external variable by name and filter it. This function is used to validate variables from insecure sources, such as user input from form. This function is very much useful to prevent some potential security threat like SQL Injection.
filter_input(type, variable, filter, options)
Parameters:
Parameter | Description |
---|---|
type | Required. The input type to check for. Can be one of the following:
|
variable | Required. The variable name to check |
filter | Optional. Specifies the ID or name of the filter to use. Default is FILTER_DEFAULT, which results in no filtering |
options | Optional. Specifies one or more flags/options to use. Check each filter for possible options and flags |
Example - filter_input()
filter_input_array() Function
The filter_input_array() function is used to get external variables (e.g. from form input) and filters them if it is specified. This function is similar to filter_input() function but the only difference is filter_input() filters a single value but in filter_input_array() filters the whole array according to options provided. It is useful for retrieving/filtering many values instead of calling filter_input() many times.
filter_input_array(type, definition, add_empty)
Parameters:
Parameter | Description |
---|---|
type | Required. The input type to check for. Can be one of the following:
|
definition | Optional. Specifies an array of filter arguments. A valid array key is a variable name, and a valid value is a filter name or ID, or an array specifying the filter, flags and options. This parameter can also be a single filter name/ID; then all values in the input array are filtered by the specified filter |
add_empty | Optional. A Boolean value. When set to TRUE it add missing keys as NULL to the return value. Default value is TRUE |