Is this type of security validation valid? (Several if verifying if VALIDATE is true)

1

Is the following correct way to validate whether input values are valid?

if(!empty($_POST))
{
    if(filter_input(INPUT_POST, 'hemocomponenteBolsa', FILTER_VALIDATE_INT))
    {
        if(filter_input(INPUT_POST, 'grupoSanguineoBolsa', FILTER_VALIDATE_INT))
        {
            if(filter_input(INPUT_POST, 'fatorRHBolsa', FILTER_VALIDATE_INT))
            {
                if(filter_input(INPUT_POST, 'dtVencimento', FILTER_SANITIZE_STRING))
                {
                    if(filter_input(INPUT_POST, 'statusBolsa', FILTER_VALIDATE_INT))
                    {
                        #CÓDIGO
                    }
                }
            }
        }
    }
else
{
    $_SESSION['msg'] = "<div class='alert alert-danger'><b>Atenção!</b>
                         Falha ao cadastrar. (Erro 007)</div>";
    header("Location: ../view/novaBolsa.php");
}

In the case here, I removed several fields for learning effect, but I have 12 inputs to be received, so I would have 12 times if(...) , correct do the previous mode or would it cause the system to be slow?

    
asked by anonymous 30.09.2017 / 15:46

1 answer

6

Use filter_input_array and then with in_array and array_values check if there is any value FALSE in the values, example :

<?php

    $filters = [
        'hemocomponenteBolsa' => FILTER_VALIDATE_INT, 
        'grupoSanguineoBolsa' => FILTER_VALIDATE_INT,
        'fatorRHBolsa' => FILTER_VALIDATE_INT,
        'statusBolsa' => FILTER_VALIDATE_INT,
        'dtVencimento' => FILTER_SANITIZE_STRING
    ];

    $result = filter_input_array(INPUT_POST, $filters);

    if (!in_array(FALSE, array_values($result), TRUE)
    {
        //#Codigo
        //A variavel $result tem os valores corretos
        $result['hemocomponenteBolsa'];
    }

Do not forget that the setting was entered within a array with the variables that come from your with the configured filters and there are other ways to configure , this is the simplest .

So your code would be very easy to maintain, inserting or removing other fields only in the variable array $filters , and you do not have to write as many decision structures ( if ) as are unnecessary in this case and they hinder the understanding of the code and its maintenance.

If you wanted the dtVencimento field to pass without value, you would have to mount an auxiliary function and if there is a value in it, filter the

30.09.2017 / 16:43