How to check POST and GET data using filter_input?

I am wondering if it is possible to get a variable, whether it is in POST or GET, and then use filter_input () to clear it.

At first I thought that $var = filter_input(INPUT_POST | INPUT_GET, "var", FILTER_SANITIZE_STRING) might work, but it is not, and the PHP manual says that you can only pass one type of input.

I also tried INPUT_REQUEST , which strangely didn't work. The function recognizes it (i.e. it does not cause an error saying that I put something wrong in $ input), but it will not receive any code. And yes, I know that I do not use INPUT_REQUEST in a live environment, I just simply tested whether this would work.

I am currently doing the following:

 $var = filter_input(INPUT_POST, "var", FILTER_SANITIZE_STRING); if(!$var) $var = filter_input(INPUT_GET, "var", FILTER_SANITIZE_STRING); 

however, with many things in PHP, there is often an easier way that will make all of this one command for me. I am wondering if this is so, can I combine them into one check? I did a quick Google search and couldn’t even find links to those who tried to do this before, not to mention the solution, so now I am contacting you with good people.

+4
source share
4 answers

He considered bad practice if you do not know if your entry is in GET or POST . You should always know, and not just arbitrarily accept anything.

+3
source

I think there is no better approach than creating a custom function with the code that you already mentioned:

 function getPostOrGet($name) { $var = filter_input(INPUT_POST, $name, FILTER_SANITIZE_STRING); if(!$var) $var = filter_input(INPUT_GET, $name, FILTER_SANITIZE_STRING); return $var; } 

And if you think this is normal, you cannot use the | operator , because then what happened, if it is defined in both.

Also note that since this is bad practice, there is no “easy” way to do this. Therefore, use a special function if you really need it, and use only the correct input type if you can.

+1
source

From what I read, you can change the POST value in your form to GET - this way you only need to accept GET - not sure if I understood it correctly.

0
source

If you deactivate your input correctly , I personally will conduct the result of filtre_input for null , because the condition if(!$var) can be caused by a false but existing value, for example 0 .

For instance:

 function getLatitude($name) { $var = filter_input(INPUT_POST, 'latitude', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); if($var === null){ $var = filter_input(INPUT_GET, 'latitude', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); } return $var; } 

With the usual condition !$var and FILTER_SANITIZE_NUMBER_FLOAT you get null instead of 0 .

0
source

Source: https://habr.com/ru/post/1494976/


All Articles