Skip to content
Advertisement

PHP How to filter ‘in a correct way’ All $_POST variables

Using Netbeans, whenever i try to access a variable in $_POST or $_GET, i’m adviced to use something like: filter_input(INPUT_POST,'id'), for ‘safety’ (i don’t think it’s any safer than using filter_input with the default NON filter, but anyways..).

This got me thinking about the answer to this post: How to grab all variables in a post (PHP)

There you have:

foreach ($_POST as $key => $value) {
    //do something
    echo $key . ' has the value of ' . $value;
}

filter_input() only works for individual variables inside $_POST

My question is, How can i re-write “$_POST as $key” with filtering to fit this supposed access standard that NetBeans is telling me about?.

Advertisement

Answer

You can filter whole $_POST using filter_input_array

$safePost = filter_input_array(INPUT_POST);

Using the second parameter you can change filter

$safePost = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

You can also define per-property filters

$safePost = filter_input_array(INPUT_POST, [
    "id" => FILTER_VALIDATE_INT,
    "name" => FILTER_SANITIZE_STRING,
    "email" => FILTER_SANITIZE_EMAIL
]);

What if I know nothing about input?

You always know something, you know what you expect to get. If the user provides an invalid input you should react to that.

If you expect an integer in the id field and the user sends you tomato, then you should reply with an error informing the user what is wrong with the request they sent.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement