How to check if the form was sent empty

1

I have a question about how to check if the form is empty.

My intention is not to check field by field, imagining that I can have N³³³ campos .

I'm trying this way:

<form method="post" name="submit" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="input_txt"/>
    <input type="text" name="input_txt2"/>
    <input type="submit" name="sub_btn"/>
</form>
<?php
if(empty($_POST))
{
    echo "empty";
}else
{
    echo "no empty";
}
?>

However, the result is always no empty .

How can I resolve this?

    
asked by anonymous 13.02.2017 / 16:29

2 answers

3

It is worth mentioning that using <input name="btn" type="submit" value="Enviar" /> , the value of btn will always be present in the $_POST vector, as PHP treats the button itself as a form entry (since it is an input ). Thus, to consider only the "real" fields of the form, you must discard such a value from the vector:

unset($_POST["btn"]);

And then check the remaining values. It is also worth noting that an empty string is considered by PHP as a possible value and therefore the empty function will always return false , since the vector will have < in> string empty. To get around this, simply filter the vector according to their values:

array_filter($_POST);

By passing the second parameter of the array_filter function, all values considered false will be removed and, in this case, empty string is by default considered false in PHP. In this way, only the duly filled fields will remain in $_POST .

The code would look something like this:

unset($_POST["sub_btn"]);

if(empty(array_filter($_POST))) {
    echo "empty";
}else {
    echo "no empty";
}
    
13.02.2017 / 16:59
2

In a very simplified way:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="input_txt"/>
    <input type="text" name="input_txt2"/>
    <button name="sub_btn"/>Enviar</button>
</form>
<?php

$formVals = array_count_values($_POST);
$key = key($formVals);

if(count($formVals) == 1)
{
    echo "empty";
}else
{
    echo "no empty";
}
?>

The variable $_POST is an Array that, whenever a POST is performed it receives the values of the fields, that is, using print_r($_POST) we will get a result similar to this:

Array ( [input_txt] => [input_txt2] => [sub_btn] => )

As [sub_btn] will always return NULL just check the amount of values present in $_POST using array_count_values , if it is only 1 value ( count($formVals) == 1 ), all fields are empty.

    
13.02.2017 / 16:47