When to use filter_input() PHP

Asked

Viewed 665 times

3

For a long time I use the $_POST[] in my applications, however I have seen that in some colleagues use the filter_input() in place of $_POST[]. I’ve already opened the PHP documentation, but I confess that I could not understand very well its use. My doubts are:

  1. What is the purpose of the filter_input();
  2. If it is valid to exchange the $_POST[] for filter_input();
  3. When should we use the filter_input();

I saw that in the documentation, highlights FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_ENCODED, FILTER_DEFAULT and FILTER_VALIDATE_EMAIL. This last use to validate e-mail:

$email = filter_input(INPUT_POST,"EmailVerificar",FILTER_VALIDATE_EMAIL);

But only the one who understood the use.

1 answer

2


So my dear, first good morning!

As you have visited PHP documentation, I’m just going to take a quick brush stroke for each item you mentioned in the topic.

1.- The filter_input() we can say that it is a junction of the variables already known by PHP programmers ($_POST, $_GET and others) into a single function and "optionally filters it (as cited in the documentation)".

2.- Yes it is really valid you make the exchange of a $_POST for one let’s suppose filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING) or filter_input(INPUT_POST, 'username', FILTER_SPECIAL_CHARS) (Being just a very basic example of how it could be used)

3.- It could be used on too many occasions, for example in a $_GET and checking whether the $_GET is numerical... $foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_NUMBER_INT);

But we have a but if chance the index does not exist... On that occasion:

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

Returns a string "" empty and generates:

Notice: Undefined index: foo

Our current, following the documentation parameters, will return only one NULL outworking:

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

Just return:

NULL

But basically the answer is: YES, you can make a simple exchange of your $_POST for filter_input(). (Including use in my projects! Kkk)


Just adding up the information (Thanking @Fox.11 for posting) if there are too many questions regarding the two filter options.

FILTER_SANITIZE

Used to clear variables:

https://www.youtube.com/watch?v=V4AnuYaSWO4

FILTER_VALIDATE

Used to validate variables:

https://www.youtube.com/watch?v=6J8lOhc1_IA

  • Good morning Rapha. Thank you! Just to add to your information, I found 02 videos that can help people who, like me, have doubts about the filter_input(). It’s them: FILTER_SANITIZE Used to clear variables: https://www.youtube.com/watch?v=V4AnuYaSWO4 FILTER_VALIDATE Used to validate variables: https://www.youtube.com/watch?v=6J8lOhc1_IA Worth a look.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.