I'm wondering if it's possible to get a variable whether it is in POST or GET and then use filter_input() to sanitize it.
At first I thought that $var = filter_input(INPUT_POST | INPUT_GET, "var", FILTER_SANITIZE_STRING)
might work, however it doesn't and the PHP manual states you can only pass one type of input.
I also tried INPUT_REQUEST
, which strangely didn't work. The function recognises it (i.e. it doesn't throw up an error saying I've put something wrong in $input), yet it won't get any code. And yes, I know not to use INPUT_REQUEST
in a live environment, I was just purely testing to see if it would work.
Currently I do 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 simpler way that will do it all for me in one command. I'm wondering if that is the case here, can I combine them into one check? I performed a cursory search on Google and couldn't even find any references to anyone trying this before, let alone a solution, so now I turn to you good folks.
It's considered bad practice if you don't know whether your input is in GET
or POST
. You should always know and not just randomly accept whatever.
I think there isn't a better approach than making a custom function with the code 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 in it is normal you can't use the |
operator because then what happened if it's defined in both.
Also note that, as it's a bad practice, it doesn't have an "easy" way of doing it. So use a custom function if you really need it, and use only the correct input type if you can.
A little bit late to the party. I had the same probem. My solution for this case is a approch like this:
$data = array_merge(filter_input_array(INPUT_POST), filter_input_array(INPUT_GET));
$var = $data["var"];
If you need to sanitize before use the options from filter_input_array: http://php.net/manual/de/function.filter-input-array.php
For example:
$args = array(
'var' => FILTER_SANITIZE_STRING
);
And combined:
$data = array_merge(filter_input_array(INPUT_POST, $args), filter_input_array(INPUT_GET, $args));
$var = $data["var"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With