Sablefoste Sablefoste - 1 month ago 6
PHP Question

When is filter_input() used versus filter_var()?

I traditionally use a

filter_var()
function for sanitizing
$_GET
and
$_POST
data, such as:

$foo = filter_var($_GET['foo'], FILTER_SANITIZE_NUMBER_INT);


but PHP also has a function
filter_input()
, which has a different syntax to accomplish the same thing:

$foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_NUMBER_INT);


Are these just synonyms? Is there an advantage to using one over the other?

I have checked the man pages, but I don't see a lot of difference (only whether/how an error is reported). Semantically/best practice, what makes the most sense?

Answer

One of the main differences is how they handle undefined variables/indexes. If $_GET['foo'] doesn't exist:

$foo = filter_var($_GET['foo'], FILTER_SANITIZE_NUMBER_INT);

Returns an empty string "" and generates:

Notice: Undefined index: foo

So you would normally need to wrap this in a if(isset($_GET['foo'])).

Whereas:

$foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_NUMBER_INT);

Returns NULL and does not generate an error.