How to know if the form is sent

Asked

Viewed 8,335 times

17

How to know when the form is sent and without input fields being empty?

I was told the isset to carry out this action but I did not understand right the use of the isset

  • 2
  • 1

    This question is being discussed at the goal: http://meta.pt.stackoverflow.com/questions/4388/ap-que-d%C3%A1-positive-all-but-no-right-e-accept-the-most-wrong-kkk

6 answers

22


Suppose a form with input field called "foo":

<form method="get" action="script.php">
<input type="text" name="foo" size="10" />
</form>

The form will send the data to the file "script.php".

Suppose this is the code of "script.php":

$campo = 'foo'; //nome do campo no formulario.

/**
Obtém o array de dados da variável global.
Note que aqui receberá tanto como GET quanto como POST ou outros métodos como PUT, DELETE, etc.
Nesse caso, o recomendado é validar o método recebido. 
Como esse não é o foco da pergunta e também para evitar escrever algo muito complexo, considerando que o AP não sabe nem o que é um isset(), vamos manter a coisa simplificada.
*/
$p = $GLOBALS['_'.$_SERVER['REQUEST_METHOD']];

/**
Verifica se o índice (o campo do fomrulário ou parâmetro de url) existe dentro da global.
*/
if (!isset($p[$campo])) {
   echo 'índice inexistente'; exit;
}

/**
Remove espaços vazios do início e do fim da string, caso existam.
Isso ajuda a definir se o valor está realmente vazio. Todavia, caso a regra de negócio permita caracteres de espaço livremente, essa verificação deve ser evitada, obviamente. 
*/
$val = trim($p[$campo]);

/**
Verifica se o valor é vazio.
*/
if(empty($val)) {
   echo 'O campo '.$campo.' está vazio'; exit;
}

/**
Por fim, o resultado final.
*/
echo 'O valor de '.$campo.' é: '.$val;

Common errors we commonly see in answers to this type of question

$valor = $_POST['valor'];

  if(empty($valor){
    echo 'vazio';
  }

Why is that wrong?

Why when the global $_POST array index is missing, an error will be triggered undefined index. When no error is triggered it is because the environment is poorly configured. As most environments are poorly configured, many end up believing that the use of the function empty(), in that case, it is appropriate.

In many forums and blogs it is common to find this as a solution, unfortunately and as a result we have this great dissemination of erroneous information.

In short, the function empty() as its name suggests, checks whether a string or array is empty. Does not check if it exists.

The function isset() means, roughly speaking "is set?".

As the function empty(), the name is suggestive and intuitive just as the documentation is very clear about its functionalities. (http://php.net/empty and http://php.net/isset)

Another error also found in the answers given here:

$nome = $_POST['nome'];
if (!isset($nome)) {
   echo 'variável vazia';
}

This will also issue error if the index is non-existent.

The right thing would be

if (!isset($_POST['nome'])) {
   echo 'variável é inexistente';
}

Note that the phrase was also incorrect. Because empty variable is different from non-existent variable.

Concluding remarks

As we can see, a simple $_GET and $_POST is much more complex than we see in most of the answers and tips on various blogs and forums.

Essential details for building a solid system.

  • Man, just so I understand, remember I’m still learning, and certain things still need to be drawn for me rsrs, but look, if I don’t just use a global variable (which from what I understand of the answer takes all the fields of the form and creates the variable with the same name... is that it?), but let’s say that each form field has a different variable, is it worth the same rule? Like, to do the right thing I have to use isset, trimand empty in all variables? + 11

  • And if it’s a number it would be nice to still add is_numeric for example? Or else it’s exaggeration?

  • I don’t think I explained it properly, let’s say that each variable is declared separately... I have stated or just with isset or with empty a ternary operator (and you always used with ifand such), I mean, my code is a m@$%$ right... If you just want to explain something here in the coments after I create another question if you think it best.... Thanks...

  • 2

    The treatment of parameters depends on the business model. Not everything you receive should necessarily be filtered, sanitized, etc.. It’s hard to try to explain in this small comment space. I think it will leave you with more questions. especially about the use of $GLOBALS. rsrs.. But to put it briefly, $GLOBALS is merely a technique for abstracting the data more dynamically. Note that there are no specific calls to $_GET or $_POST. I wrote in a generic way that allows flexibility. But this is subject for another conversation. Impracticable to post here.

  • Daniel, I created a little question (rsrs) about my doubts. thanks for the moment! abs

9

$_POST is a array and you can use count( $_POST ) to check if something has been sent, otherwise 0 will be returned.

But empty( $_POST ) will also make the check, with the difference that will return trueor false and is a more generic function (you can use with other types of variables).

To know if there is a key in the array, you can use array_key_exists( 'key', $_POST ), but you can also use isset( $_POST[ 'chave' ] ) which is more generic.

isset returns TRUE if the variable (and key / informed property) has been set. empty returns TRUE if NOT set or its value is false: false, 0, '0', '', null or empty array - [] / array().

isset or empty, more generic, are faster than array_key_exists() (https://stackoverflow.com/questions/6884609/array-key-existskey-array-vs-emptyarraykey) and subtly faster than count() (https://stackoverflow.com/questions/2216110/checking-for-empty-arrays-count-vs-empty).

Therefore, recommend issetor empty instead of array_key_exists or count.

OBS: I thank the Daniel Omine by his questioning, which led me to the correction and improvement of my answer.

4

In the file you receive the data via POST, you can use:

if (getenv('REQUEST_METHOD') == 'POST') { /* faz alguma coisa */ }

NOTE: getenv() does not work with ISAPI

And one more option, which is the most used, is to use isset. isset() returns true if the variable was set and false if it was not set.

if (isset($_POST['name'])) { /* faz alguma coisa */ }

Isset documentation()

3

The simplest way to know if a post was sent is through REQUEST_METHOD.

Try to do something like:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

}

REQUEST_METHOD indicates the method used in the request. There are no restrictions on its use.

-2

Just a hint:

Instead of checking if the fields were sent in blank, it would not be better to prevent this from happening?

function valida() {

  var nome = document.getElementById('nome').value,
      sobrenome = document.getElementById('sobrenome').value;
 
  if( ! nome ) {
    alert('Nome não foi preenchido');
    return false;
  } else if( ! sobrenome ) {
      alert('Sobrenome não foi preenchido');
    return false;
  } else {
    alert('Seu formulário foi enviado!');
    return true;
  }

}
<form action="" method="get" onsubmit="return valida();">
  Nome:
  <br>
  <input id="nome" name="nome" type="text" />
  <br><br>
  Sobrenome:
  <br>
  <input id="sobrenome" name="sobrenome" type="text" />
  <br><br>
  <input type="submit" value="Enviar" />
</form>

Do a Javascript form validation before submitting as in the example above. In Google you find many examples.

  • How about you bring an example and edit your answer? So it gets more complete, you contribute with the site and mainly with several other people who have/will have this same doubt.

  • I edited the post and inserted an example as requested!

-4

You can use isset to check if a field has been "sent" or can also use empty.

Using isset:

$nome = $_POST['nome'];
if (!isset($nome)) {
   echo 'variável vazia';
}

Note that before the function isset I put an exclamation mark, this causes the attribute to return the opposite, ie, false. example:

if (isset($nome))...// Se a variável nome conter algum valor...
if (!isset($nome))...// Se a variável nome não conter alguma valor...

using empty:

$nome = $_POST['nome'];
if (empty($nome)) {
    echo 'variavel vazia';

You can also use the same logic for the empty, for example:

if (empty($nome))...// Se a variável nome estiver vazia...
if (!empty($nome))...// Se a variável NÃO estiver vazia...
  • 3

    The use of empty() for this case is inadvisable.

  • 5

    And another point is, is using isset in the wrong place.. srrs would be isset($_POST...)

Browser other questions tagged

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