Icons
Questions
Snippets
The php filters is used to validate & filter data coming from insecure sources like user input.
Php has many functions for filtering data, list of some of them.
filter_has_var()
This function is used to check if a variable of a specific input type exist. It takes two arguments.
Arguments | Description |
---|---|
Type | (a) INPUT_GET (b) INPUT_POST (c) INPUT_COOKIE |
Variable | Value of the variable. |
filter_list()
Returns unlist of all supported filters in php.
Example
<?php
foreach(filter_list() as $l) {
echo $l.'<br>';
}
?>
filter_input()
Gets an external variable ( example from form input ) an optionally filters it.
filter_input(
int $type,
string $var_name,
int $filter = FILTER_DEFAULT,
array|int $options = 0
):
Parameters | Description |
---|---|
type | One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. |
var_name | Name of a variable to get. |
filter | The ID of the filter to apply. The Types of filters manual page lists the available filters. If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default. |
options | Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. |
<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>
filter_var()
Filters a variable with a specified filter.
filter_var(variable, filtername, options)
Parameters | Description |
---|---|
value | Value to filter. Note that scalar values are converted to string internally before they are filtered. |
filter | The ID of the filter to apply. The Types of filters manual page lists the available filters. If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default. |
options | Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callable type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it. |
<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
?>
Example of filter_validate_input
<?php
$i = 5.25;
if(filter_var($i, FILTER_VALIDATE_INT)) {
echo 'Integer value';
}
else {
echo 'Not an integer value';
}
?>