The advantage of using filter_input
is in the ease of applying filters in your string .
The same result can be obtained with the function filter_var
, which implements the constants of FILTER
The filter_input
would have the same function as:
// Sem filter_input
$email = filter_var($_GET['email'], FILTER_VALIDATE_EMAIL);
// Usando filter input
$email = filter_input(INPUT_GET , 'email', FILTER_VALIDATE_EMAIL);
The filter_*
functions are few used by beginners, but they are quite useful. In the above example for example, php already validates if input
is an email, without having to resort to Regular Expressions monstras .
With a little creativity, using a cousin of the filter_input
function, filter_input_array
, we can validate our forms with a very expressive and elegant code.
Adapted example of documentation:
<?php
$data = array(
'product_id' => 'libgd<script>',
'component' => '10',
'versions' => '2.0.33',
'testscalar' => array('2', '23', '10', '12'),
'testarray' => '2',
);
$args = array(
'product_id' => FILTER_SANITIZE_ENCODED,
'component' => array('filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
'options' => array('min_range' => 1, 'max_range' => 10)
),
'versions' => FILTER_SANITIZE_ENCODED,
'doesnotexist' => FILTER_VALIDATE_INT,
'testscalar' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_SCALAR,
),
'testarray' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
)
);
$myinputs = filter_var_array($data, $args);
var_dump($myinputs);
It results in the following array already treated:
array(6) {
["product_id"]=>
array(1) {
[0]=>
string(17) "libgd%3Cscript%3E"
}
["component"]=>
array(1) {
[0]=>
int(10)
}
["versions"]=>
array(1) {
[0]=>
string(6) "2.0.33"
}
["doesnotexist"]=>
NULL
["testscalar"]=>
bool(false)
["testarray"]=>
array(1) {
[0]=>
int(2)
}
}