-1

I have an script that sometimes takes more than 40 seconds to run. But the microtime thing returns less thatn 1 second.

First issue is WHY IS THIS TAKING SO LONG???? and second issue is why microtime don't return time correctly?

  <?
  $inicio = microtime(true);
  session_start();
  header('Content-Type: text/html; charset=utf-8');
  include 'coneccion-base-mails.php';
  include 'coneccion.php';
  include 'funciones.php';



  $id = $_POST["id"];

  //recuperamos los datos del envio
  $R = $mysqli->query("SELECT * FROM envios WHERE id=".$id."")->fetch_array();

  $remitente = $R["remitente"];
  $lista = $R["lista"];
  $asunto = $R["asunto"];
  $cuerpo = $R["cuerpo"];
  $sustituto = $R["sustituto"];

  $contactos = array();



  //ahora creamos cargamos la lista
  if($lista=="Todos"){
      $result = $mysqli->query("SELECT * FROM listas WHERE usuario='".$_SESSION["usuario"]."'");
      while($R = $result->fetch_array()){
          $dato = array($R["nombre"],$R["apellido"],$R["mail"]);
          array_push($contactos,$dato);
      }
  }
  else{
      $result = $mysqli->query("SELECT * FROM segmentos WHERE titulo='".$lista."' and usuario='".$_SESSION["usuario"]."'");
      $R = $result->fetch_array();
      $idsegmento = $R["id"];
      $result = $mysqli->query("SELECT * FROM listasegmentos WHERE idsegmento=".$idsegmento."");
      while($R = $result->fetch_array()){
          $dato = array(nombreContacto($R["idcontacto"]),apellidoContacto($R["idcontacto"]),mailContacto($R["idcontacto"]));
          array_push($contactos,$dato);
      }
  }

  //ya tenemos los contactos,

  //ahora los recorremos uno a uno, fijandonos si ya fue enviado ese mail, si fue enviado vamos al siguiente, sino lo mandamos y cortamos.
  $total = count($contactos);
  $mm = 0;

  if( mailsEnviadosEstaHora() < $limiteMailsPorHora){
      foreach($contactos as $contacto){
          $nombre = $contacto[0];
          $apellido = $contacto[1];
          $mail = $contacto[2];
          if(mailEnviado($mail)=="no"){
              if(strpos($mail,";")===false){

                  enviarMail($nombre." ".$apellido." <".$mail.">",$mail,$nombre);

              }
              else{
                  $mails = explode(";",$mail);
                  $comp = "";
                  foreach($mails as $mailss){
                      if($comp == ""){
                          $comp = $nombre." ".$apellido." <".$mailss.">";
                      }
                      else{
                          $comp .= ",".$nombre." ".$apellido." <".$mailss.">";
                      }
                  }
                  enviarMail($comp,$mail,$nombre);
              }
              break;
          }
          else{
              $mm++;
          }
      }


      if($mm == $total){
          $mysqli->query("UPDATE envios SET estado='enviada' WHERE id=".$id."");
          echo "actualizar";
      }
  }
  else{
      //se llego al limite de mails por hora
      echo "limite";
  }






  function marcarEnviado($mail){
      global $mysqli;
      global $id;
      global $remitente;
      global $lista;
      global $asunto;
      global $cuerpo;
      global $mm;
      global $total;
      global $inicio;


      $fecha = date("Y")."-".date("m")."-".date("d");

      $mysqli->query("INSERT INTO procesoenvio (idenvio,destinatario,estado,fecha,hora,solohora) VALUES (".$id.",'".$mail."','enviado','".$fecha."','".date('H:i:s')."','".date('H')."')");

      $caca = $mm+1;
      echo $caca." / ".$total;
      $actual = microtime(true);
  $totalsss= $actual- $inicio;
  echo 'Tiempo : '.$totalsss.' segundos<br>';

  }

  function enviarMail($para,$mail,$nombre){
      global $mysqli;
      global $id;
      global $remitente;
      global $lista;
      global $asunto;
      global $cuerpo;
      global $sustituto;



      if($nombre==''){
          $nombre = $sustituto;
      }


      //from
      $from = array();
      $_datos = explode("<",$remitente);
      $_nombre = trim($_datos[0]);
      $_mail = $_datos[1];
      $_mail = trim(str_replace(">","",$_mail));
      $from[$_mail] = $_nombre;

      $cuentas = explode("---",$_SESSION['correo']);

      foreach($cuentas as $cuenta){

          $correo = explode("|||",$cuenta);
          $username = $correo[0];
          $password = $correo[1];
          if($username == $_mail){
              break;
          }
      }



      //

      require_once 'swiftmailer-master/lib/swift_required.php';

      // Create the mail transport configuration
      $transport = Swift_SmtpTransport::newInstance("mail.dxxxxxxxxxxx.com",25);
      $transport->setUsername($username);
      $transport->setPassword($password);

      // Create the message
      $message = Swift_Message::newInstance();

      $destinatarios = explode(",",$para);
      $destin = array();
      foreach($destinatarios as $destinatario){
          $s = strpos($destinatario,"<");
          if($s===false){
              array_push($destin,$destinatario);
          }
          else{
              $_datos = explode("<",$destinatario);
              $_nombre = trim($_datos[0]);
              $_mail = $_datos[1];
              $_mail = trim(str_replace(">","",$_mail));
              $destin[$_mail] = $_nombre;
          }

      }


      $message->setTo($destin);
      $message->setSubject($asunto);

      $message->setFrom($from);

      // adjuntos!!!
      $ruta = '../../panel/envios/adjuntos/' . $id . '/'; // Relative to the root

      if(file_exists($ruta)){ // Abrir archivos
          $n = 0;

          $archivos = array();

          foreach (new DirectoryIterator($ruta) as $file) {
              if($file->isDot()) continue;
              array_push($archivos,$file->getFilename());
          }
          sort($archivos);
          foreach($archivos as $archivo){

              $message->attach(Swift_Attachment::fromPath('http://xxxxxxxxxxxxxxxxxxxx.com'.str_replace('../../','/',$ruta).str_replace(' ','-',$archivo)));
              $n+=1;
              //break;
          }

          if($n==0){
              //no hay fotos en la carpeta 

          }

      }
      $cuerpoPersonalizado = str_replace('[[[Nombre]]]',$nombre,$cuerpo);
      $message->setBody($cuerpoPersonalizado,'text/html');
      $msg = $message->toString();
      $msg = str_replace('http://xxxxxxxxxxxx.com/img.php?i','#',$msg);
      $verificacion = base64_encode($id.'|||'.$mail);
      $cuerpoPersonalizado = str_replace('numeroidentificacion',$verificacion,$cuerpoPersonalizado);
      $message->setBody($cuerpoPersonalizado,'text/html');
      // Send the email
      $mailer = Swift_Mailer::newInstance($transport);

      //$mailer->send($message) or die($msg);

      $mailer->send($message);



      marcarEnviado($mail);




      $hostname = '{localhost:143}Sent Items';
      $conn = imap_open($hostname,$username,$password) or die('No se pudo conectar con: usuario: '.$username.' y clave: '.$password.' ' . imap_last_error());   

      imap_append($conn, '{localhost:143}Sent Items', $msg, "\\Seen") or die("error");


  }





  ?>
Alvaro Hernandorena
  • 610
  • 1
  • 5
  • 18
  • You should use `echo 'Tiempo : '.round($totalsss, 5).' segundos
    ';`.
    – barell Jun 10 '14 at 20:07
  • 2
    There's a whole lot going on there. Take parts out until it no longer takes a long time, and then focus on the last chunk your removed before it got fast. Any of your queries (among other things) could be the cause of the slowness. – Patrick Q Jun 10 '14 at 20:14
  • the strangest thing is that sometimes the script runs fast, normal, 1 second, and other times it runs in 40 seconds or more. The hosting company told me that it was not a limitation, the only mail limitation in the server is 500 mails per hour, but I am sending lot less than that. – Alvaro Hernandorena Jun 10 '14 at 21:08

1 Answers1

2

As an important tangent to your question, please ensure you cleanse your data - those $_POSTs are wide open for SQL injection: Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?

Think about using PDO prepared statements. It's more secure (helps prepare statements against SQL injection) and makes transactions easy (for several repeated queries).

As for your answer, I think you are misunderstanding what microtime() returns. I've included a link to format the number of microseconds in the way you may expect.

php microtime() format value

Community
  • 1
  • 1
rroberts
  • 74
  • 3
  • rroberts thank you for the advice on the $_POSTs been wide open, I would have to fix that, right now all this is thing I am making is not open to public, is for internal use, so I will not worry about SQL injection, but I will have to deal with it in the future. thank you – Alvaro Hernandorena Jun 12 '14 at 19:35
  • That's a huge symptom of wrong software engineering practice, of course. There is absolutely no reason to not use a safe practice and instead default to a dangerous one. – Jan Kundrát Jun 27 '14 at 20:06