Question:
For a long time I use $_POST[]
in my applications, however I have seen that some colleagues use filter_input()
instead of $_POST[]
. I've already opened the PHP documentation , but I confess that I couldn't quite understand its use. My questions are:
- What is the use of
filter_input()
; - If it is valid to change
$_POST[]
byfilter_input()
; - When should we use
filter_input()
;
I saw that in the documentation, it highlights FILTER_SANITIZE_SPECIAL_CHARS
, FILTER_SANITIZE_ENCODED
, FILTER_DEFAULT
and FILTER_VALIDATE_EMAIL
. This last use to validate email:
$email = filter_input(INPUT_POST,"EmailVerificar",FILTER_VALIDATE_EMAIL);
But only this one that I understood the use.
Answer:
So my dear, first good morning!
As you've already visited PHP documentation , I'm just going to give you a quick brushstroke for each item you've cited in the thread.
1.- The filter_input()
can be said to be a combination of variables already known by us PHP programmers ($_POST, $_GET and others) into a single function and "optionally filters it (as mentioned in the documentation)".
2.- Yes it is really valid for you to exchange a $_POST for one let's suppose filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING)
or filter_input(INPUT_POST, 'username', FILTER_SPECIAL_CHARS)
(It is just a very basic example of how it could to be used)
3.- It could be used in too many occasions, like for example in a $_GET and checking if the $_GET is numeric… $foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_NUMBER_INT);
But we have a but if the index doesn't exist… On this occasion:
$foo = filter_var($_GET['foo'], FILTER_SANITIZE_NUMBER_INT);
Returns an empty string ""
and generates:
Notice: Undefined index: foo
Our current one, following the documentation parameters, will only return a NULL
result:
$foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_NUMBER_INT);
Returns only:
NULL
But basically the answer is: YES , you can do a simple switch from your $_POST
to filter_input()
. (I even use it in my projects! Kkk)
Just adding up the information (Thanks to @Fox.11 for posting) in case there are too many questions about 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