Use the filter_input with array_filter ($ _ POST)

0

I have a form where you have enough fields, for this, I'm doing it this way:

require_once('classes/metodosClass.php');
$metodos = new metodosClass();
if($_POST["Submit"] == "Cadastrar"){
  $dados = array_filter($_POST);
  echo $metodos->cadastrarDados($dados);
}

And in the method dataData ($ data):

public function cadastrarDados(array $dados){
   $nome = mysqli_real_escape_string($this->conexao,$dados["Nome"]);
   $email = mysqli_real_escape_string($this->conexao,$dados["Email"]);
   $cpf = mysqli_real_escape_string($this->conexao,$dados["CPF"]);
   ....
   // Depois faço a inclusão no BD
}

I'm just wanting to apply FILTER_SANITIZE and FILTER_VALIDATE to those fields. How could I apply in this situation since I am using the array? I thought about doing it that way, but I do not know if it's the right one. I'll just put the example I thought of doing:

if($_POST["Submit"] == "Cadastrar"){      
   $nome = filter_input(INPUT_POST,'nome',FILTER_SANITIZE_SPECIAL_CHARS);
   $emailLimpar = filter_input(INPUT_POST,'email',FILTER_SANITIZE_EMAIL);
   $emailValidar = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL);
   ....
   if($emailValidar == true){
      $erro = "Favor colocar o e-mail corretamente!"; 
   }else if(...){
    .......
   }else{
     $dados = array_filter($_POST);
     echo $metodos->cadastrarDados($dados);
   }
}
    
asked by anonymous 02.12.2018 / 16:37

1 answer

1

So, let's assume you are using the MVC architecture, let's follow the same precepts ...

Assuming the $_POST call is on the Controller , we will basically just turn it into a array() and the rest we leave it to the Model to do, even filter ...

Basically what would we do? What you've already done:

if($_POST["Submit"] == "Cadastrar"){
  $dados = array_filter($_POST);
  echo $metodos->cadastrarDados($dados);
}

Coming in Model with array() filtering:

public function cadastrarDados(array $dados){
    $dadosFiltrado = filter_input(INPUT_GET, $dados, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

    // Faça o restante dos filter_input aqui com o $dadosFiltrado (Inclusive as validações e verificações do email e ETC)
}

See if it works with your system! :)

    
02.12.2018 / 17:27