Use filter_input with array_filter($_POST)

Asked

Viewed 119 times

0

I have a form where there are plenty of fields, for this, I’m doing 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 registered method ($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
}

Only I’m willing to apply the FILTER_SANITIZE and FILTER_VALIDATE for these fields. How could I apply in this situation since I’m using the array? I thought I’d do it this way, but I don’t know if it’s the right one. I’ll just set the example I thought I’d set:

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);
   }
}
  • I did a test and unfortunately it didn’t work. The filter_input() loses its value when it is passed to the array_filter(). There would be some solution to that?

1 answer

1


Okay, so let’s assume you’re using architecture MVC, let’s follow the precepts of it...

Supposing the call of $_POST is in the Controller, basically we’ll just turn him into a array() and the rest we leave to the Model filter, including...

Basically what would we do? What have you ever done:

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

And coming in the Model with the filtration of array():

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! :)

  • 1

    Perfect Rapha. Thanks again!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.