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

1

Checking a contact form with success and error messages

Attention to the corrections I have 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

New 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;
    
asked by anonymous 28.05.2018 / 16:15

1 answer

3
  

Your Resolução com PHP e JS still does not seem appropriate because it sends email even with wrong validation.

Front-end

  • Simply log in to the console and change your form, such as removing REQUIRED, or increasing the maxlength that the mail will be sent. Therefore it is also important to validate in% with%
  • If you fill in the field Back-end with spaces only the email will be sent.
  • Back-end

      

    Sessions in PHP are not "insecure" however 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><scriptsrc="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><?phpif(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 submitting direct to specific part of the page.

    • In a URL, a game symbol of the old ( assunto/mensagem ) directs a browser to a specific location on a page or site.

      1 - Put a # into the form, example id

      2 - In the action of the form id="form"

    Example

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