Problems PHP form

1

I have a form on the same page, and the problem I have is the following if I update to keep sending me the email constantly, if I make a header and redirecciono miss the message sent successfully. I need some solution.

And another problem that I want to solve by pressing the submit button on the form takes me to the beginning of the web and I want it to remain as it is in the position where the form is and I do not scroll to the top of the page and have to go back down again to see the form and the success messages or errors. This is the code.

<?php 

  $errores = '';
  $enviado = '';


  if (isset($_POST['submit'])) {
    $nombre = $_POST['nombre'];
    $email = $_POST['email'];
    $area = $_POST['area'];

    if (!empty($nombre)) {
      $nombre = trim($nombre);
      $nombre = filter_var($nombre, FILTER_SANITIZE_STRING);
    } else {
      $errores .= 'Por favor ingresa un nombre <br />';
    }
    if (!empty($email)) {
      $email = filter_var($email, FILTER_SANITIZE_EMAIL);

      if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errores .= 'Por favor ingresa un correo valido <br />';
      }
    } else {
       $errores .= 'Por favor ingresa un correo <br />';
    }

    if(!empty($area)){
      $area = htmlspecialchars($area);
      $area = trim($area);
      $area = stripcslashes($area);
    } else {
      $errores .= 'Por favor ingresa el mensaje <br />';
    }

    if(!$errores){
      $enviar_a = '[email protected]';
      $asunto = 'Correo enviado desde mi pagina';
      $mensaje_preparado = "De: $nombre \n";
      $mensaje_preparado .= "Correo: $email \n";
      $mensaje_preparado .= "Mensaje ". $area;

      mail($enviar_a, $asunto, $mensaje_preparado);
      $enviado = true;
    }

}

 require 'index.php';



 ?>

and this the html form

<div class="row">

  <?php if (!empty($errores)): ?>
    <div class="error">
      <?php echo $errores; ?>    
    </div>
    <?php elseif($enviado): ?>
       <div class="success">
         <p>Enviado con extio</p>  
       </div>
  <?php endif ?>   

  <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
    <div class="row">
      <div class="input-field col s12">
        <i class="material-icons prefix">account_circle</i>
        <input type="text" class="validate" id="nombre" name="nombre" value="<?php if(!$enviado && isset($nombre)) echo $nombre ?>">
        <label for="icon_prefix nombre" data-error="wrong" data-success="right">Introduce tu nombre </label>
      </div>
    </div>
    <div class="row">
      <div class="input-field col s12">
        <i class="material-icons prefix">email</i>
        <input type="email" class="validate" id="email" name="email" value="<?php if(!$enviado && isset($email)) echo $email ?>">
        <label for="icon_prefix1 email">Introduzca su email</label>
      </div>
    </div>
    <div class="row">
      <div class="input-field col s12">
        <i class="material-icons prefix">mode_edit</i>
        <textarea class="materialize-textarea" id="area" name="area"><?php if(!$enviado && isset($area)) echo $area ?></textarea>
        <label for="icon_prefix2 area">Escriba su mensaje</label>
      </div>
      <div class="center-align">
        <button class="btn waves-effect waves-light deep-purple lighten-2 yellow-text text-accent-1" type="submit" id="submit" name="submit">Enviar
          <i class="material-icons right">send</i>
        </button>
      </div>
    </div>

    
asked by alfonso Perez 09.11.2016 в 18:47
source

1 answer

2

What happens is that after the information is sent by POST, if you reload the page it will be forwarded and therefore will re-enter the IF, in fact you should see an alert saying that if you want to resend the data.

A possible solution is to leave independent the file that has the Html form and the file that processes the sending of the information by POST, and that you send the messages by GET.

For example:

form.php

$error = isset( $_GET['error']) ? $_GET['error'] : '';
$exito = isset( $_GET['exito']) ? $_GET('exito') : '';

// PHP7 equivale a: $error = isset( $_GET['error']) ?? '';

<form action="procesar_form.php" method="post">

// Si hubo un error, te imprimirá el mensaje, sino, imprimirá cadena vacía, igual con exito ...
echo $error;
echo $exito;
//el resto de tu formulario....

What this code does is that it first evaluates if there is a variable called error and another call success (which are the ones that you will send, now I show how), if their values exist they will be assigned to later print them.

Otherwise, $ error and $ success are assigned empty string. If you notice, the form will send the data to proces_form.php :

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

  // Asignación y validación de datos. Digamos que el nombre está vacío...

  // Rediriges a form.php con una variable GET llamada error que es la que cachará
  if ( !empty($nombre)) {
    header('location: form.php?error=nombre vacio');
  }

  // Resto del código si pasa la validación, enviar email, etc. 
}

Another way that can be more efficient to validate data would be something like

if ( empty( $nombre) or empty( $email) or empty( $mensaje) )
{
  header('location: form.php?error=debes llenar todos los datos');
}

And for the success message, it would be like this:

// Ya no necesitas evaluar $errores porque si los hay, redirecciona y no continua el flujo

$enviar_a = '[email protected]';
$asunto = 'Correo enviado desde mi pagina';
$mensaje_preparado = "De: $nombre \n";
$mensaje_preparado .= "Correo: $email \n";
$mensaje_preparado .= "Mensaje ". $area;

// Mejor aquí validar si se envia el correo
if ( mail($enviar_a, $asunto, $mensaje_preparado))
   header('location: form.php?exito=Enviado correctamente :) ');
else
   header('location: form.php?error=Huno un error al enviar el correo :( ');

That way, even if you reload the form page nothing will happen unless there is a GET variable it will continue to print.

Note: Here I assume that the files form.php and proces_form.php are in the same folder / directory.

    
answered by 09.11.2016 в 20:03