I have a registration form. There are also two fields that are email and confirm e-mail. How do I see if the two emails are the same in php and display an error message if they are not the same?
I have a registration form. There are also two fields that are email and confirm e-mail. How do I see if the two emails are the same in php and display an error message if they are not the same?
To retrieve the values typed in the server-side form with PHP, you can use the superglobal variable $_POST
. It would look something like:
$email = $_POST["email"];
$confirmacaoDeEmail = $_POST["confirmacao_de_email"];
And to check if they are different:
if ($email != $confirmacaoDeEmail) {
echo "Os e-mails informados não coincidem";
}
However, this does not guarantee that the values are, in fact, emails. The user could type the number 2 in the two fields, which would be the same and would not give an error. To validate if they are valid emails, you can use the filter_input
function:
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$confirmacaoDeEmail = filter_input(INPUT_POST, "confirmacao_de_email", FILTER_VALIDATE_EMAIL);
// Verifica se são e-mails inválidos:
if (!$email || !$confirmacaoDeEmail) {
echo "O e-mail não é um e-mail válido";
}
// Verifica se são diferentes:
if ($email != $confirmacaoDeEmail) {
echo "Os e-mails informados não coincidem";
}
But reconsider using JavaScript to also , this validation is still on the client side because you would prevent the client from making an unnecessary request to the server. The sooner you inform the user of the error, the sooner it will be fixed.