Using filter_input_array(INPUT_POST,"var_name") vs. $_POST

Asked

Viewed 1,121 times

1

I have the following variable input in my form:

<input class="caption_text" type="text" name="caption[]" required/>

That I create dynamically with JS.

After submitting I test the following:

$mycaption = \filter_input_array(\INPUT_POST, 'caption');
foreach ($mycaption as $eachInput) {
    echo "Caption " . $eachInput . "<br>";
}

I found that the above code did not work.

However, unsaying $_POST, so:

$cpost = $_POST["caption"];

foreach ($cpost as $eachInput) {
    echo "Caption " . $count. " - " . $eachInput . "<br>";
}

Then it works as expected.

Can someone please tell me why the first approach doesn’t work?

  • 3

    What are those inverted bars in your code?

  • Is using the filter_input_array and having it validate what ? Of course the return will be null, try adding some expression to validate what you expect to receive in this field.

  • Hi, I don’t want to validate anything, just get the variable submitted. It is recommended to no longer use the $_POST direct global variable and yes through a filter_input.

1 answer

0

I made a test simulating the code that posted and formulated the code below using the function:

<?php
$filtro = array( 
    'caption' => array(
        # aqui pode variar de acordo com o valor esperado do seu input
        'filter' => FILTER_VALIDATE_STRING,
        'flags' => FILTER_REQUIRE_ARRAY
    )
);
$form = filter_input_array(INPUT_POST, $filtro); 
if (array_key_exists("caption", $form))
{
    foreach($form['caption'] ...)
    {
         # ...
    }
}

Exit

<?php
var_dump($form);
# array(1) { ["caption"]=> array(2) { [0]=> int(2) [1]=> int(3) } }
  • 1

    Hello Wilian, thanks for your help.

  • Since the Netbeans IDE warns: "do not access superglobal $_POST array directly", I am using "filter_input" as recommended. For all the variables of my form I do this and it works right. However, for this field which is an array (caption[ ]) it does not work. This caption is an array that creates dynamically and receives normal text, just to describe the selected images. For now, I will continue accessing like this: $caption = $_POST['caption'];

Browser other questions tagged

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