Avoid forwarding mail when reloading the page

1

A question would have some way of avoiding email resending (I am using the PHPMailer library) when reloading the page without using a button, since I am developing a notification system, but I have a problem that the notifications are they keep on the page until the users see them and change, then when the user reloads or re-enters the page and the notifications are still there, they send me the email again.

I tried to increment a variable each time the email was sent, and so when the variable is greater than 1, I did not send more emails, but when the page is reloaded it does not save the value of the incremented variable.

I appreciate your answers.

This is code:

<?php 

$timeActual= time(); 
$hoy = date('Y-m-d');
$dia3 = date('Y-m-d', strtotime('+3 day'));

foreach($documentos as $user){

$fechaDB = $user->fecha_fin;

if ($fechaDB <> "0000-00-00") {

    if( $fechaDB <= $hoy ) {

?> 

<div class="container col-md-offset-0">
  <div  class="alert alert-info  alert-dismissible col-lg-6">
    <button type="button" class="close" data-dismiss="alert" aria-
 hidden="true">&times;</button>
    <h4><i class="icon fa fa-check"></i> Alerta!</h4>
    <?php echo "<b>CLIENTE: </b>".$user->nombre;?>
    <br><b>NOTIFICACION: </b>Contrato terminado <?php  echo " - "."<b>FECHA 
FIN: </b>".$user->fecha_fin; ?>
  </div>
</div>

<?php

$mail = new PHPMailer();

$mail->isSMTP();
$mail->SMTPOptions = array(
'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
 )
);
 $mail->SMTPAuth = true;
 $mail->SMTPSecure = 'tls';//Modificar
 $mail->Host = 'smtp.gmail.com';//Modificar
 $mail->Port = '587';//Modificar
 $mail->Username = '[email protected]'; //Modificar
 $mail->Password = 'Aplicativomc'; //Modificar

 $mail->setFrom('[email protected]', 'Sistema control de 
 facturación');//Modificar

 $mail->addAddress('[email protected]', ' Sr. Omar Rincon');//
 $mail->addAddress('[email protected]', ' Sr. Eduardo 
 Ramirez');//Modificar
 $mail->IsHTML(true);

 $html='


 <html>
 <head>
  <title></title>
 </head>
 <body>
  <h1>Mensaje de prueba</h1>
  <p>Hola mundo XD</p>
  <img 
 src="https://pbs.twimg.com/profile_banners/3140696879/1429203807/1500x500" 
 width="300" height="100">

 </body>
 </html>


';
$mail->Subject = 'Notificación';//Modificar
$mail->Body = $html; //Modificar



$mail->CharSet = 'UTF-8';

$intentos=0; 

if($intentos == 0){
$intentos++;
$mail->send();
 echo 'Enviado';
   return true;
 } else {  
echo 'Error';
return false;

}

 }else if ($fechaDB == $dia3){

 ...
 ?>

EDITION SOLUTION

Create a table called notifications with the fields ID, VALOR, ID_DOCUMENTOS as the notifications are according to the date in the table NOTIFICATIONS I made the following query

$sql = "SELECT id, valor, id_documentos from notificacion WHERE id = 
id and id_documentos = '$user->id'"; 

This query what it does is to bring me the data from the NOTIFICATIONS table according to the id_documents, and finally the condition

if($row["valor"] == 0){
$mail->send();

$sql = "INSERT INTO notificacion (valor, alerta, id_documentos) VALUES 
(1,$user->id')";
$resultado = $mysqli->query($sql);

}else{

}   

which looks at me if the alert that is assigned to that document has the value field in 0 ... if so send me the email and make the insert with the field sent in 1, then when I reload the page , as the field is in 1 it does not send me again.

    
asked by O.Eduard 18.01.2018 в 15:41
source

2 answers

3

The problem is as follows, when you reload the page $intentos=0; is again set to 0 so you will always enter the if. You could use session variables.

This is how they are defined:

<?php
    //Inicias la sesion
    session_start();
    //Compruebas si se ha definido la variable

    if (!isset($_SESSION['count'])) {
        $_SESSION['count'] = 0; // si no lo esta la dejas a 0
    } else {
        $_SESSION['count']++; // si ya existe sumas uno
    }
?>


Si lo aplicamos a tu codigo deberia quedarse algo asi:
//Inicias la sesion
session_start();
//Compruebas si se ha definido la variable
if (!isset($_SESSION['enviado']) || $_SESSION['enviado'] == false) {
  $_SESSION['enviado'] = true; // si no lo esta la dejas a 0
  $mail->send();
  echo 'Enviado';
  return true;
} else {
  echo 'Error';
  return false;
}

I have changed it to a Boolean variable because you do not need to know how many times it has been sent, but if it has already been sent.

EDITION

Seeing that you have to create a new table in the database, I indicate the way I would do it.

Note: I do not know the structure of your database, so this solution will have to be adapted

Let's say you have a user table (to which you send the notification).

This table could be like this:

USUID   USUNOMBRE   USUAPELLIDO USUAPELLIDO2

Then another notification table, with the id of the notification and its message.

Something like this:

NOTIID  NOTIDESC

Finally you create a table of Emails, this could have a date of shipment and the id of the user and notifications (if users have more than one email you could also add the email field) and to ensure a Boolean field to tell us if it has been sent successfully or not.

It would stay like this:

EMAILID USUID   NOTIID  FECENVIO    ENVIADO

That would be the part of the database, as in the first example I explain how to do it with the session variable now I will do it (without complicating a lot with the sql) with the database.

The first thing you should do is to collect in variables the information you need, that is, the id of the user to whom the notification is sent, the id of the notification and the most important thing and what you are interested in, if has been sent.

With a sql more or less like this you could check if that notification has been sent.

SELECT USUID, NOTIID, ENVIADO FROM EMAIL WHERE USUID = ? and NOTIID = ? and ENVIADO = TRUE

So, if you get any registration, it will be that the email has already been sent and also successfully, in the case that you do not have any registration you should do a $mail->send(); and add a new record to the email table in the case that you never would have tried to send that email or an update in the case that the previous shipment was FALSE .

Finally I indicate how to send the email and check if the shipment was correct or not:

//Antes de realizar este bloque de código, debes comprobar si existe una
//fila con los datos que vas ha enviar y el campo enviado en true.
//Si existe, no debe ejecutar el bloque ya que el email ya ha sido enviado.
if(!$mail->send()) { //Intenta enviar el correo
  //Si da error enviandolo
  //SQL INSERT (campo enviado false)      
} else {
  //Si se envia correctamente
  //Comprobar si tiene el campo enviado en false
  if($enviado == false){
     //SQL (campo enviado true)
  }else{
     //SQL INSERT (campo enviado true)
  }
}
    
answered by 18.01.2018 / 16:28
source
0

Without the code, we can only give you opinions. In your case I would try to make a variable = 0. At the moment that the client wants to send the mail (or when it is time), the variable is set to 1. Then it would put the function that sends it within a:

IF (variable == 1 ){
  enviaMail();
}

When the page is refreshed the variable returns to 0 and the mail is not sent.

    
answered by 18.01.2018 в 15:49