Foros del Web » Programando para Internet » PHP »

Como validar en PHPMailer

Estas en el tema de Como validar en PHPMailer en el foro de PHP en Foros del Web. hola a todos, Tengo un formulario en php con la libreia de phpmailer, pero tengo un problema: No se como hacer las validaciones!! Enviar envia, ...
  #1 (permalink)  
Antiguo 10/02/2012, 11:03
 
Fecha de Ingreso: febrero-2010
Mensajes: 113
Antigüedad: 14 años, 2 meses
Puntos: 5
Pregunta Como validar en PHPMailer

hola a todos,

Tengo un formulario en php con la libreia de phpmailer, pero tengo un problema: No se como hacer las validaciones!!

Enviar envia, y recibo todo muy bien, pero las validaciones del nombre, correo, telefono, mail, titulo... no las detecta!!!! En cuanto esta escrito cualquier mail lo envia sin haber completado el formulario (o incluso vacio).

Para validar uso el metdodo POST.

Código PHP:
Ver original
  1. .....................
  2.     $mail -> Username = '[email protected]';
  3.     $mail -> Password = 'password';
  4.     $mail -> MsgHTML($body1);
  5.     if ($mail -> Send())
  6.     {
  7.         $msg=" Enviado.";
  8.     }else{
  9.         $msgerror=" Error, no enviado.";
  10.     }
  11.    
  12. }

Cuando falta algun dato por poner, salta lo de "Error, no enviado" e vez de saltar "Escriba su nombre" me esplico?

No queria pegar todo el codigo que es muy extenso, muchas gracias a todos!
  #2 (permalink)  
Antiguo 10/02/2012, 12:36
Colaborador
 
Fecha de Ingreso: mayo-2008
Ubicación: $MX['VZ']['Xalapa']
Mensajes: 3.005
Antigüedad: 15 años, 11 meses
Puntos: 528
Respuesta: Como validar en PHPMailer

Bueno, si te "esplicas", pero debes saber que phpmailer es una librería para el envío de emails, nada más, phpmailer no sabe de buenas a primeras si un usuario no llenó un formulario completamente, eso lo debes validar tú.
  #3 (permalink)  
Antiguo 10/02/2012, 12:50
Avatar de DooBie  
Fecha de Ingreso: septiembre-2004
Mensajes: 1.101
Antigüedad: 19 años, 7 meses
Puntos: 71
Respuesta: Como validar en PHPMailer

Pero, tu haces la validación antes?
  #4 (permalink)  
Antiguo 10/02/2012, 13:28
 
Fecha de Ingreso: febrero-2010
Mensajes: 113
Antigüedad: 14 años, 2 meses
Puntos: 5
Respuesta: Como validar en PHPMailer

Ya lo tengo validado antes, pero no lo detecta!

Este es el código completo:

Código PHP:
Ver original
  1. function valida_email($email) {
  2. $re= '#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si';
  3. return preg_match($re, $email);
  4. }
  5.  
  6. function validarTelefono($phone)
  7. {
  8. $reg = "#^\(?\d{3}\)?[\s\.-]?\d{3}[\s\.-]?\d{4}$#";
  9. return preg_match($reg, $phone);
  10. }
  11.  
  12. $submit=$_POST['Submit'];
  13. if($submit == Submit)
  14. {
  15. $status = "OK";
  16. $email=$_POST['email'];
  17. $message=$_POST['message'];
  18. $subject=$_POST['subject'];
  19. $name=$_POST['name'];
  20. $phone=$_POST['phone'];
  21. $title=$_POST['title'];
  22. $otros2=$_POST['otros2'];
  23.  
  24. $msg="";
  25. $msgerror="";
  26. //error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
  27.  
  28.  
  29.  
  30. if ( strlen($name) < 1 )
  31. {
  32. $msgerror .="* Nombre invalido.<BR />";
  33. $status= "NOTOK";
  34. }
  35.  
  36.  
  37. //if (!stristr($email,"@") OR !stristr($email,"."))
  38. if(!valida_email($email))
  39. {
  40. $msgerror .="* Mail incorrecto.<BR />";
  41. $status= "NOTOK";
  42. }
  43.  
  44. //if ( strlen($phone) < 9 )
  45. if(validarTelefono($phone))
  46. {
  47. $msgerror .="*Telefono compuesto por 9cifras.<BR />";
  48. $status= "NOTOK";
  49. }
  50.  
  51.  
  52. if($title=="Opcion2")
  53. {
  54. $headers4="[email protected]";
  55. }else if($title=="Opcion1"){
  56. $headers4="[email protected]";
  57. }else if($title=="error"){
  58. $status="NOTOK";
  59. $msgerror .="* Seleccione un titulo.<BR />";
  60. }
  61.  
  62.  
  63. if ( strlen($message) < 10 )
  64. {
  65. $msgerror .="* Mensaje minimo 10 caracteres.<BR/>";
  66. $status= "NOTOK";
  67. }
  68.  
  69.  
  70. $body1="<html>
  71. <head>
  72. <p><font face=Tahoma, Helvetica, sans-serif size=2 color=#333333>
  73. <strong>Formulari de Contacte Web:</strong></font><br>
  74. <br><hr width=450px align=left><br>
  75. <font face=Tahoma, Helvetica, sans-serif size=2>
  76.  
  77. <title>Formulario de Contacto Web</title>
  78. </head>
  79. <body>
  80. <strong>Nombre:</strong> $name.<br>
  81. <strong>Tel&eacute;fono:</strong> $phone.<br>
  82. <strong>T&iacute;tulo:</strong> $title: $otros2.<br>
  83. <strong>Email:</strong> $email.<br>
  84. <strong>Mensaje:</strong> $message.</font></p>
  85. </body>
  86. </html> ";
  87.  
  88. require_once 'phpmailer/class.phpmailer.php';
  89.  
  90. $mail = new PHPMailer ();
  91. $mail -> SetFrom ("[email protected]","[email protected]");
  92. $mail -> AddAddress ("$email","$name");
  93. $mail -> Subject = "$title: $otros2";
  94. $mail -> IsHTML (true);
  95. $mail -> IsSMTP();
  96. $mail -> Host = 'mail.dominio.com';
  97. $mail -> Port = 2626;
  98. $mail -> SMTPDebug = 2;
  99. $mail -> SMTPAuth = true;
  100. $mail -> Username = '[email protected]';
  101. $mail -> Password = 'password';
  102. $mail -> MsgHTML(file_get_contents('www.dominio.com/archivos/recibido.html'));
  103. if ($mail -> Send())
  104. {
  105. $msg=" Enviado.";
  106. }else{
  107. $msgerror=" Error inesperado.";
  108. }
  109.  
  110. $mail = new PHPMailer ();
  111. $mail -> SetFrom ("[email protected]","[email protected]");
  112. $mail -> AddAddress("$headers4");
  113. $mail -> Subject = "$title: $otros2";
  114. $mail -> IsHTML (true); // pones (true) en caso de usar formato HTML
  115. $mail -> IsSMTP();
  116. $mail -> Host = 'mail.dominio.com';
  117. $mail -> Port = 2626;
  118. $mail -> SMTPAuth = true;
  119. $mail -> Username = '[email protected]';
  120. $mail -> Password = 'password';
  121. $mail -> MsgHTML($body1);
  122. $mail -> Send();
  123. }
  #5 (permalink)  
Antiguo 10/02/2012, 14:01
Avatar de DooBie  
Fecha de Ingreso: septiembre-2004
Mensajes: 1.101
Antigüedad: 19 años, 7 meses
Puntos: 71
Respuesta: Como validar en PHPMailer

ups.....!!!!
  #6 (permalink)  
Antiguo 10/02/2012, 15:44
 
Fecha de Ingreso: febrero-2010
Mensajes: 113
Antigüedad: 14 años, 2 meses
Puntos: 5
Respuesta: Como validar en PHPMailer

hola de nuevo!

a ver si juntos lo conseguimos!!!

pues estuyve buscando, y en este mismo foro hace 2 años han tenido el mismo problema, aqui el enlace http://www.forosdelweb.com/f18/desac...3/#post3239122

la "solución" es cambiar la clase de phmailer:


Código PHP:
Ver original
  1. require_once 'phpmailer/class.phpmailer.php';
  2.  
  3.     require_once 'phpmailer/class.phpmailer.php';
  4.    
  5.     class ValidatingWPHPMailer extends PHPMailer
  6.     {
  7.  
  8.     public function AddValidAddress($email = '', $name = '', $title = '', $message = '', $phone = '')
  9.     {
  10.         if ( ! empty($email) and ! empty($name) and ! empty($title) and ! empty($message) and ! empty($phone))  {
  11.            $this->AddAddress($email,$name,$title,$phone,$message);
  12.         } else {
  13.              throw new phpmailerException('Email and FullName are required');
  14.         }
  15.     }
  16.     }  
  17.  
  18. $mail = new ValidatingWPHPMailer ();
  19. .........................

he agregado eso justo antes del comienzo del comienzo, pero me da el siguiente error (en el navegador):

"Fatal error: Uncaught exception 'phpmailerException' with message 'Email and FullName are required' in /home/user/public_html/es/contact5.php:109 Stack trace: #0 /home/user/public_html/es/contact5.php(116): ValidatingWPHPMailer->AddValidAddress('', 'Juanito') #1 {main} thrown in /home/user/public_html/es/contact5.php on

Alguien se le ocurre alguna cosa??

Gracias.
  #7 (permalink)  
Antiguo 10/02/2012, 15:47
Avatar de DooBie  
Fecha de Ingreso: septiembre-2004
Mensajes: 1.101
Antigüedad: 19 años, 7 meses
Puntos: 71
Respuesta: Como validar en PHPMailer

Antes quise contestar, pero me confundí...
El problema lo tienes en que envías dos veces el correo, además, haces la validación, haciendo un NOTOK, pero no lo compruebas antes de hacer el envío.
Fíjate en eso, que ese es el problema, no te compliques con incluir otro fichero ni nada, es un problema de lógica tuya, no de la clase phpmailer
  #8 (permalink)  
Antiguo 10/02/2012, 15:52
 
Fecha de Ingreso: febrero-2010
Mensajes: 113
Antigüedad: 14 años, 2 meses
Puntos: 5
Respuesta: Como validar en PHPMailer

si, lo envio 2 veces aprpoposito, uno le llega al cliente, y otro me llega a mi con sus datos.

Antes el formulario lo tenia con la funcion mail() y me funcionaba correctamente.

Pero ahora adaptarlo con PHPMailer.... en las validaciones es donde mas me esta costando.....

Lo del NOTOK en mail me ha funcionado, aqui debo cambiarlo?
  #9 (permalink)  
Antiguo 10/02/2012, 16:06
Avatar de DooBie  
Fecha de Ingreso: septiembre-2004
Mensajes: 1.101
Antigüedad: 19 años, 7 meses
Puntos: 71
Respuesta: Como validar en PHPMailer

Código PHP:
Ver original
  1. if($tatus == "OK"){
  2. $body1="<html>
  3. <head>
  4. <p><font face=Tahoma, Helvetica, sans-serif size=2 color=#333333>
  5. <strong>Formulari de Contacte Web:</strong></font><br>
  6. <br><hr width=450px align=left><br>
  7. <font face=Tahoma, Helvetica, sans-serif size=2>
  8.  
  9. <title>Formulario de Contacto Web</title>
  10. </head>
  11. <body>
  12. <strong>Nombre:</strong> $name.<br>
  13. <strong>Tel&eacute;fono:</strong> $phone.<br>
  14. <strong>T&iacute;tulo:</strong> $title: $otros2.<br>
  15. <strong>Email:</strong> $email.<br>
  16. <strong>Mensaje:</strong> $message.</font></p>
  17. </body>
  18. </html> ";
  19.  
  20. require_once 'phpmailer/class.phpmailer.php';
  21.  
  22. $mail = new PHPMailer ();
  23. $mail -> SetFrom ("[email protected]","[email protected]");
  24. $mail -> AddAddress ("$email","$name");
  25. $mail -> Subject = "$title: $otros2";
  26. $mail -> IsHTML (true);
  27. $mail -> IsSMTP();
  28. $mail -> Host = 'mail.dominio.com';
  29. $mail -> Port = 2626;
  30. $mail -> SMTPDebug = 2;
  31. $mail -> SMTPAuth = true;
  32. $mail -> Username = '[email protected]';
  33. $mail -> Password = 'password';
  34. $mail -> MsgHTML(file_get_contents('www.dominio.com/archivos/recibido.html'));
  35. if ($mail -> Send())
  36. {
  37. $msg=" Enviado.";
  38. }else{
  39. $msgerror=" Error inesperado.";
  40. }
  41.  
  42. $mail = new PHPMailer ();
  43. $mail -> SetFrom ("[email protected]","[email protected]");
  44. $mail -> AddAddress("$headers4");
  45. $mail -> Subject = "$title: $otros2";
  46. $mail -> IsHTML (true); // pones (true) en caso de usar formato HTML
  47. $mail -> IsSMTP();
  48. $mail -> Host = 'mail.dominio.com';
  49. $mail -> Port = 2626;
  50. $mail -> SMTPAuth = true;
  51. $mail -> Username = '[email protected]';
  52. $mail -> Password = 'password';
  53. $mail -> MsgHTML($body1);
  54. $mail -> Send();
  55. }
  56. }else{
  57. // No ha pasado la validación, aquí haces lo que tu quieras.
  58. }

Algo así (añade la parte de código que falta al principio).
  #10 (permalink)  
Antiguo 10/02/2012, 16:27
 
Fecha de Ingreso: febrero-2010
Mensajes: 113
Antigüedad: 14 años, 2 meses
Puntos: 5
Respuesta: Como validar en PHPMailer

Vale, lo puse asi, tal cual como me has dicho. Pero ocurren 2 cosas:



Código PHP:
Ver original
  1. function valida_email($email) {
  2.     $re= '#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si';
  3.     return preg_match($re, $email);
  4.     }
  5.      
  6.     function validarTelefono($phone)
  7.     {
  8.     $reg = "#^\(?\d{3}\)?[\s\.-]?\d{3}[\s\.-]?\d{4}$#";
  9.     return preg_match($reg, $phone);
  10.     }
  11.      
  12.     $submit=$_POST['Submit'];
  13.     if($submit == Submit)
  14.     {
  15.     $status = "OK";
  16.     $email=$_POST['email'];
  17.     $message=$_POST['message'];
  18.     $subject=$_POST['subject'];
  19.     $name=$_POST['name'];
  20.     $phone=$_POST['phone'];
  21.     $title=$_POST['title'];
  22.     $otros2=$_POST['otros2'];
  23.      
  24.     $msg="";
  25.     $msgerror="";
  26.     //error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
  27.      
  28.      
  29.      
  30.     if ( strlen($name) < 1 )
  31.     {
  32.     $msgerror .="* Nombre invalido.<BR />";
  33.     $status= "NOTOK";
  34.     }
  35.      
  36.      
  37.     //if (!stristr($email,"@") OR !stristr($email,"."))
  38.     if(!valida_email($email))
  39.     {
  40.     $msgerror .="* Mail incorrecto.<BR />";
  41.     $status= "NOTOK";
  42.     }
  43.      
  44.     //if ( strlen($phone) < 9 )
  45.     if(validarTelefono($phone))
  46.     {
  47.     $msgerror .="*Telefono compuesto por 9cifras.<BR />";
  48.     $status= "NOTOK";
  49.     }
  50.      
  51.      
  52.     if($title=="Opcion2")
  53.     {
  54.     $headers4="[email protected]";
  55.     }else if($title=="Opcion1"){
  56.     $headers4="[email protected]";
  57.     }else if($title=="error"){
  58.     $status="NOTOK";
  59.     $msgerror .="* Seleccione un titulo.<BR />";
  60.     }
  61.      
  62.      
  63.     if ( strlen($message) < 10 )
  64.     {
  65.     $msgerror .="* Mensaje minimo 10 caracteres.<BR/>";
  66.     $status= "NOTOK";
  67.     }
  68.      
  69.     if ($status == "OK"){
  70.     $body1="<html>
  71.    <head>
  72.    <p><font face=Tahoma, Helvetica, sans-serif size=2 color=#333333>
  73.    <strong>Formulari de Contacte Web:</strong></font><br>
  74.    <br><hr width=450px align=left><br>
  75.    <font face=Tahoma, Helvetica, sans-serif size=2>
  76.    
  77.    <title>Formulario de Contacto Web</title>
  78.    </head>
  79.    <body>
  80.    <strong>Nombre:</strong> $name.<br>
  81.    <strong>Tel&eacute;fono:</strong> $phone.<br>
  82.    <strong>T&iacute;tulo:</strong> $title: $otros2.<br>
  83.    <strong>Email:</strong> $email.<br>
  84.    <strong>Mensaje:</strong> $message.</font></p>
  85.    </body>
  86.    </html> ";
  87.      
  88.     require_once 'phpmailer/class.phpmailer.php';
  89.      
  90.     $mail = new PHPMailer ();
  91.     $mail -> SetFrom ("[email protected]","[email protected]");
  92.     $mail -> AddAddress ("$email","$name");
  93.     $mail -> Subject = "$title: $otros2";
  94.     $mail -> IsHTML (true);
  95.     $mail -> IsSMTP();
  96.     $mail -> Host = 'mail.dominio.com';
  97.     $mail -> Port = 2626;
  98.     $mail -> SMTPDebug = 2;
  99.     $mail -> SMTPAuth = true;
  100.     $mail -> Username = '[email protected]';
  101.     $mail -> Password = 'password';
  102.     $mail -> MsgHTML(file_get_contents('www.dominio.com/archivos/recibido.html'));
  103.     if ($mail -> Send())
  104.     {
  105.     $msg=" Enviado.";
  106.     }else{
  107.     $msgerror=" Error inesperado.";
  108.     }
  109.      
  110.     $mail = new PHPMailer ();
  111.     $mail -> SetFrom ("[email protected]","[email protected]");
  112.     $mail -> AddAddress("$headers4");
  113.     $mail -> Subject = "$title: $otros2";
  114.     $mail -> IsHTML (true); // pones (true) en caso de usar formato HTML
  115.     $mail -> IsSMTP();
  116.     $mail -> Host = 'mail.dominio.com';
  117.     $mail -> Port = 2626;
  118.     $mail -> SMTPAuth = true;
  119.     $mail -> Username = '[email protected]';
  120.     $mail -> Password = 'password';
  121.     $mail -> MsgHTML($body1);
  122.     $mail -> Send();
  123.     }

1- He solucionado que me valide los datos
2- Cuando esta todo rellenado y le doy a enviar, no envia nada ni dice enviado, carga el formulario de nuevo con los mismo datos y no llega ni envia nada...

se me ha olvidado algo?

Muchissimas gracias!!!

Etiquetas: formulario, html, phpmailer
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:11.