How do I know when the form is submitted and the input fields are blank?
I was asked to isset
to perform this action but I did not understand the right use of isset
How do I know when the form is submitted and the input fields are blank?
I was asked to isset
to perform this action but I did not understand the right use of isset
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 "script.php" code:
$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 this wrong?
Because when the global array index $ _POST is non-existent, a undefined index
error will be triggered. When it does not fire the error is because the environment is misconfigured. Since most environments are misconfigured, many end up believing that the use of the empty()
function is appropriate in this case.
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 empty()
function as its name suggests, checks to see if a string or array is empty. It does not check if it exists.
The isset()
function means, roughly "is it set?".
Like the empty()
function, the name is suggestive and intuitive as the documentation is very clear about its functionality. ( link and link )
Another error also found in the answers given here:
$nome = $_POST['nome'];
if (!isset($nome)) {
echo 'variável vazia';
}
This will also issue an error if the index is nonexistent.
The correct one would be
if (!isset($_POST['nome'])) {
echo 'variável é inexistente';
}
Note that the sentence was also incorrect. Because empty variable is different from non-existent variable.
Final remarks
As you can see, a simple $ _GET and $ _POST is much more complex than we see in most answers and tips on blogs and forums.
These are essential details for building a solid system.
$_POST
is an array and you can use count( $_POST )
to check if something has been sent; otherwise, it returns 0.
But empty( $_POST )
will also check, with the difference that it will return true
or false
and is a more general function (you can use it 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 variable (and key / property entered) has been set. empty
returns TRUE if it was NOT set or its value is false: false, 0, '0', '', null
or empty array - [] / array()
.
isset
or empty
, in addition to being generic, are faster than array_key_exists()
( link ) and subtly faster than count()
( link ).
I recommend isset
or empty
instead of array_key_exists
or count
.
OBS : I thank Daniel Omine for his questioning, which led me to correct and improve my answer.
In the file you receive the data via POST, you can use:
if (getenv('REQUEST_METHOD') == 'POST') { /* faz alguma coisa */ }
OBS: getenv () does not work with ISAPI
And one more option, which is the most used, is to use isset. The isset () returns true if the variable was set and false if it was not defined.
if (isset($_POST['name'])) { /* faz alguma coisa */ }
The simplest way to know if a post has been sent is through REQUEST_METHOD
.
Try to do something like:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}
REQUEST_METHOD
indicates which method is used in the request. There are no restrictions on its use.
Accompanying the idea of colleagues, it is worth remembering that it is good to also place trim () where you remove the empty spaces, which would prevent someone from pressing the space bar, which will also be interpreted as a character. I also advise you to use a captcha. Google itself provides one for free. recaptcha Google . I also advise you to use the filter_input () filter_input PHP
Just a tip:
Instead of checking if the fields were sent in white, would not it be better to prevent them from occurring?
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>
Make a form validation in javascript before submitting as in the example above. On Google you find many examples.
You can use isset
to check if a field was "sent" or you 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 point, this causes the following attribute to return the opposite, that is, 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 empty
, for example:
if (empty($nome))...// Se a variável nome estiver vazia...
if (!empty($nome))...// Se a variável NÃO estiver vazia...