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

Viewed 19430

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?.

3 Answers

You can use something like that:



        $methods = (string)$_SERVER['REQUEST_METHOD'];

        $vars_dl = [];

        if( in_array( $methods, ['POST', 'GET'] ) ) {

            switch( $methods ) {

                case 'POST':

                    $post_vars = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING | FILTER_SANITIZE_FULL_SPECIAL_CHARS | FILTER_SANITIZE_ENCODED, FILTER_REQUIRE_ARRAY ) ?? [];

                    $vars_dl = [ $post_vars, 'p' ];

                    break;

                case 'GET':

                    $get_vars = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING | FILTER_SANITIZE_FULL_SPECIAL_CHARS | FILTER_SANITIZE_ENCODED, FILTER_REQUIRE_ARRAY ) ?? [];

                    $vars_dl = [ $get_vars, 'g' ]; 

                    break;

            }

        }
        else {

            exit('<h1>ACCESS Exception :: method '. $methods .' blocked!</h1>');

        }

You can use array_map() function to apply custom filter function to all array values of posted data:

$_POST['Users'] = array_map('clean_string', $_POST['Users']);

And here is the snipped of clean_string()function:

<?php 
function clean_string($string, $mode = "strip") {       
        switch ($mode) {
                //Keep characters like é and д
                default:
                case "strip":
                $filter = array("flags"=> FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_BACKTICK);
                break;
                //Keep characters like é and д
                case "encode":
                $filter = array("flags"=> FILTER_FLAG_ENCODE_LOW|FILTER_FLAG_ENCODE_AMP); 
                break;
        }
        return filter_var(trim($string), FILTER_SANITIZE_STRING, $filter);      
    }
Related