If all fields are valid send notification and send email if no errors are shown

Asked

Viewed 124 times

1

Verification of a contact form with success messages and errors

Attention the corrections I’ve made over time!

PHP CODE

 if (isset($_POST['contact'])) {

  $nomecomp = test_input($_POST["nomecomp"]);
  if (!preg_match("/^[a-zA-Z ]*$/",$nomecomp)) {
  $nomecompErr = "Apenas letras e espaços permitidos"; 
}

  $email = test_input($_POST["email"]);
 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
 $emailErr = "Email inválido"; 
  }
 $assunto = test_input($_POST["assunto"]);
 if (!preg_match("/^[a-zA-Z ]*$/",$assunto)) {
 $assuntoErr = "Apenas letras e espaços permitidos com máximo de 25 
 carácteres";
 }

  $mensagem = test_input($_POST["mensagem"]);
  if (!preg_match("/^[a-zA-Z ]*$/",$mensagem)) {
  $mensagemErr = "Apenas letras e espaços permitidos";  
 }
else
 {

 echo '<script>',
 'jsFunction();',
 '</script>';
 $mailto = "[email protected]";
  $headers = "From:". $email;
  $txt = "Recebes-tes um email de ". $nomecomp . ".\n\n".$mensagem;
  mail($mailto, $assunto,$txt,$headers);
}

  }
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
 $data = htmlspecialchars($data);
return $data;
   }

?>

FORM

      <form method="post" role="form" class="contactForm" action="">
      <div class="col-md-6 col-sm-6 col-xs-12 left">
        <div class="form-group">
            <span class="errormessage">* <?php echo $nomecompErr;?> *</span>
          <input type="text" name="nomecomp" class="form-control form" 
        id="name" placeholder="Nome Completo"  REQUIRED />

        </div>
        <div class="form-group">
            <span class="red">* <?php echo $emailErr;?>*</span>
          <input type="email" class="form-control" name="email" id="email" 
    placeholder="Email"REQUIRED />
        </div>
        <div class="form-group">
                         <span class="error">* <?php echo $assuntoErr;?>* 
   </span>
          <input type="text" class="form-control" name="assunto" 
   id="subject" placeholder="Assunto" maxlength="25" REQUIRED/>

        </div>
      </div>
      <div class="col-md-6 col-sm-6 col-xs-12 right">
        <div class="form-group">
              <span class="error">* <?php echo $mensagemErr;?>*</span>
          <textarea class="form-control" name="mensagem" rows="5"  
     placeholder="Mensagem" REQUIRED></textarea>

        </div>
      </div>

      <div class="col-xs-12">
        <!-- Button -->
        <button type="submit" id="submit" name="contact" class="form 
   contact-form-button light-form-button oswald light fundoazul">Enviar 
    email</button>
      </div>
     </form>

JS

     function jsFunction() {
         $.bootstrapGrowl("A sua mensagem foi enviada com  sucesso!", { type: 'success' });
       }, 1000;

    </script>

Library

     <script src="js/jquery.bootstrap-growl.min.js" type="text/javascript"> 
    </script>

Resolution with PHP and JS

Novo Javascript

$( document ).ready(function() {



 var aux= "<?php echo($_SESSION['varphp']); ?>";

if(aux == 1) {               
                $.bootstrapGrowl("A sua mensagem foi enviada com sucesso", { 
type: 'success' }); 
     }
    });   

     </script>

PHP

Declare the session variable

    $_SESSION["varphp"]=0;

And change this:

   echo '<script>',
   'jsFunction();',
   '</script>';

For this reason:

     $_SESSION["varphp"]=1;
  • email is being sent correctly?

  • Yes, I’m already in my domain!

  • I’m trying to solve my problem differently now!

  • Edited answer! and with the explanation of how to send the user, after submission, to the part of the page where the form is

1 answer

3


Your Resolução com PHP e JS still doesn’t seem appropriate, as sends email even with wrong validation.

Front-end

  1. Just log into the console and change your form, such as removing REQUIRED, or increasing the maxlength the mail will be sent. Therefore it is also important to validate Back-end
  2. If you fill in the field assunto/mensagem only with spaces the mail will be sent.

Back-end

Sessions in PHP are not "insecure" but the way you program can cause a headache

Proposed solution

<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://ifightcrime.github.io/bootstrap-growl/jquery.bootstrap-growl.min.js"></script>


<?php
if (isset($_POST['contact'])) {

$situacao="Enviar";

  $nomecomp = test_input($_POST["nomecomp"]);
  if(strlen($nomecomp)<=2){
     $nomecompErr ="Preencha o nome com no mínimo 3 caracteres.";
     $situacao="naoEnviar";
     $nomecomp="";
  }elseif(!preg_match("/^[a-zA-Z ]*$/",$nomecomp)) {
     $nomecompErr = "Apenas letras e espaços permitidos"; 
     $situacao="naoEnviar";
  }

  $email = test_input($_POST["email"]);
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
     $emailErr = "Email inválido"; 
     $situacao="naoEnviar";
  }

  $assunto = test_input($_POST["assunto"]);
  if ( (strlen($assunto)<=2) || (strlen($assunto)>25) ){
     $assuntoErr = "Preencha o campo assunto com no mínimo 3 caracteres e no máximo 25 caracteres";
     $situacao="naoEnviar";
  }elseif(!preg_match("/^[a-zA-Z ]*$/",$assunto)) {
     $assuntoErr = "Apenas letras e espaços permitidos com máximo de 25 carácteres";
     $situacao="naoEnviar";
  }

  $mensagem = test_input($_POST["mensagem"]);
  if(strlen($mensagem)<=10){
     $mensagemErr = "Preencha o campo mensagem com no mínimo 10 caracteres.";  
     $situacao="naoEnviar";
  }elseif(!preg_match("/^[a-zA-Z ]*$/",$mensagem)) {
     $mensagemErr = "Apenas letras e espaços permitidos";  
     $situacao="naoEnviar";
  }

  //se tudo está ok envia email e apresenta mensagem de sucesso
  if ($situacao=="Enviar"){
      //mensagem na tela
      echo "<script>
      $(function() {
         $.bootstrapGrowl(\"A sua mensagem foi enviada com sucesso\", { type: 'success' });
     });
     </script>";

     //envio de email
     $mailto = "[email protected]";
     $headers = "From:". $email;
     $txt = "Recebes-tes um email de ". $nomecomp . ".\n\n".$mensagem;
     mail($mailto, $assunto,$txt,$headers);

     //com o envio do email corretamente, anulamos as variaveis para limpar os campos
     $nomecomp = "";
     $email = "";
     $assunto = "";
     $mensagem = "";

  } 

}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

?>


<form method="post" role="form" class="contactForm" action="">
    <div class="col-md-6 col-sm-6 col-xs-12 left">

       <div class="form-group">
          <span class="errormessage">* <?php echo $nomecompErr;?> *</span>
          <input type="text" name="nomecomp" class="form-control form" 
          id="name" placeholder="Nome Completo" value="<?php echo $nomecomp;?>"  REQUIRED />
      </div>

      <div class="form-group">
          <span class="red">* <?php echo $emailErr;?>*</span>
          <input type="email" class="form-control" name="email" id="email" 
          placeholder="Email" value="<?php echo $email;?>" REQUIRED />
      </div>

      <div class="form-group">
          <span class="error">* <?php echo $assuntoErr;?>* </span>
          <input type="text" class="form-control" name="assunto" 
          id="subject" placeholder="Assunto" maxlength="25" value="<?php echo $assunto;?>" REQUIRED/>
      </div>

   </div>

   <div class="col-md-6 col-sm-6 col-xs-12 right">
      <div class="form-group">
         <span class="error">* <?php echo $mensagemErr;?>*</span>
         <textarea class="form-control" name="mensagem" rows="5"  
         placeholder="Mensagem" REQUIRED><?php echo $mensagem;?></textarea>
       </div>
   </div>

   <div class="col-xs-12">
        <!-- Button -->
        <button type="submit" id="submit" name="contact" class="form 
        contact-form-button light-form-button oswald light fundoazul">Enviar 
        email</button>
   </div>

</form>      

After submission to specific part of the page.

  • In a URL, a game symbol of old (#) directs a browser to a specific location on a page or website.

    1 - Place a id in the form, example id="form"

    2 - No action of the form <?php echo $_SERVER['PHP_SELF']."#form"; ?>

Example

<form method="post" role="form" class="contactForm" action="<?php echo $_SERVER['PHP_SELF']."#form"; ?>" id="form">

Browser other questions tagged

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