Php Filters

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.

ArgumentsDescription
Type(a) INPUT_GET
(b) INPUT_POST
(c) INPUT_COOKIE
VariableValue 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
):

ParametersDescription
typeOne of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
var_nameName of a variable to get.
filterThe 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.
optionsAssociative 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)

ParametersDescription
valueValue to filter. Note that scalar values are converted to string internally before they are filtered.
filterThe 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.
optionsAssociative 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';
}
?>

kabeer

Added  Jul 25, 12:28 am

Article tags

×
Google login
SignUp with Email
X