Use filter_input(FILTER_SANITIZE_NUMBER_INT) in an array with integer type entries

Asked

Viewed 364 times

1

I have the following form:

<form action="<?=PATH_ROOT?>professor/cadastrar" method="post">
     Matrícula:
     <input type="text" name="matricula">

     <br><br>
     Nome:
     <input type="text" name="nome">

     <br><br>
     Turmas:<br>
     <select name="turmas[]" multiple="multiple">
          <?=$this->optionsTurma?>
     </select>

     <br><br>
     <input type="submit" value="Cadastrar">
</form>

Where the select classes[] will have a dynamic size, ie can be 1, 2, 3, 4, ... , because it’s a bank table.

And I’m modifying the validation using filter_input(); being like this:

if($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST)) {

     $post['matricula'] = filter_input(INPUT_POST, 'matricula', FILTER_SANITIZE_NUMBER_INT);
     $post['nome'] = filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_STRING);
     $post['turmas'] = filter_input(INPUT_POST, 'turmas', FILTER_SANITIZE_NUMBER_INT);

     if ($this->model->save($post))
          echo '<script>alert("Cadastrado com sucesso!");</script>';
     else
          echo '<script>alert("Erro ao cadastrar.");</script>';
}

Man $post['turmas'] will always return item(s) of the whole type. The problem is that it always returns boolean false I believe that for the reason that FILTER_SANITIZE_NUMBER_INT in an array.

$post['turmas'] = filter_input(INPUT_POST, 'turmas', FILTER_SANITIZE_NUMBER_INT);

How can I give a FILTER_SANITIZE_NUMBER_INT for each item in my class array brought from the form, it is possible?

1 answer

2


Place FILTER_REQUIRE_ARRAY as the fourth argument of the function filter_input.

$post['turmas'] = filter_input(INPUT_POST, 'turmas', FILTER_SANITIZE_NUMBER_INT, FILTER_REQUIRE_ARRAY);

Browser other questions tagged

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