Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 436
Sablefoste Avatar asked Oct 26 '16 18:10

Sablefoste


People also ask

What is the use of the Filter_var () and filter_input () functions in PHP?

filter_var. If a variable doesn't exist, the filter_input() function returns null while the filter_var() function returns an empty string and issues a notice of an undefined index.

Which function is used to get a specific external variable by name and optionally filter it?

The filter_input() function gets an external variable (e.g. from form input) and optionally filters it. This function is used to validate variables from insecure sources, such as user input.

What is filtering input?

Input filtering is the method by which you validate all incoming data and prevent any invalid data from being used by your application. It's very similar in theory to how water filtering works, where impurities in water are not allowed to pass.


1 Answers

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.

Note: The filter_input function does not operate on the current $_GET and $_POST superglobals, rather it is prepopulated and independent of those arrays.

If $_GET['foo'] does not exist but is created in the script, it will not be seen by filter_input:

$_GET['foo'] = 1;
$foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_NUMBER_INT);

Will return null.

like image 97
AbraCadaver Avatar answered Oct 17 '22 02:10

AbraCadaver