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

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.


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>');

        }