You are on page 1of 14

Proyecto:

Lista de Correos

ndice
1. 2. 3. 4. 5. 6. Base de Datos....................................................................................................................3 Ficheros PHP .....................................................................................................................4 Modificacin del fichero php.ini ........................................................................................7 Insercin de Datos y comprobacin ...................................................................................8 Envo de un correo .......................................................................................................... 10 Comprobacin de mails correctos ................................................................................... 11

Ivn Martn Valderas

Pgina 2

Lista de Correos
1. Base de Datos
Creamos nuestra base de datos en mysql para poder almacenar a los suscriptores:

2. Ficheros PHP
Manage.php
<?php //set up a couple of functions function doDB() { global $mysqli; //connect to server and select database; you may need it $mysqli = mysqli_connect("localhost", "root", "", "mailproyect"); //if connection fails, stop script execution if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } } function emailChecker($email) { global $mysqli, $check_res; //check that email is not already in list $check_sql = "SELECT id FROM SUBSCRIBERS WHERE email = '".$email."'"; $check_res = mysqli_query($mysqli, $check_sql) or die(mysqli_error($mysqli)); } //determine if they need to see the form or not if (!$_POST) { //they need to see the form, so create form block $display_block = " <form method=\"POST\" action=\"".$_SERVER["PHP_SELF"]."\"> <p><strong>Your E-Mail Address:</strong><br/> <input type=\"text\" name=\"email\" size=\"40\"> <p><strong>Action:</strong><br/> <input type=\"radio\" name=\"action\" value=\"sub\" checked> subscribe <input type=\"radio\" name=\"action\" value=\"unsub\"> unsubscribe <p><input type=\"submit\" name=\"submit\" value=\"Submit Form\"></p> </form>"; } else if (($_POST) && ($_POST["action"] == "sub")) { //trying to subscribe; validate email address if ($_POST["email"] == "") { header("Location: manage.php"); exit; } else { //connect to database doDB(); //check that email is in list emailChecker($_POST["email"]); //get number of results and do action if (mysqli_num_rows($check_res) < 1) { //free result mysqli_free_result($check_res); //add record $add_sql = "INSERT INTO subscribers (email) VALUES('".$_POST["email"]."')"; $add_res = mysqli_query($mysqli, $add_sql)

Ivn Martn Valderas

Pgina 4

Lista de Correos
or die(mysqli_error($mysqli)); $display_block = "<p>Thanks for signing up!</p>"; //close connection to MySQL mysqli_close($mysqli); } else { //print failure message $display_block = "<p>You're already subscribed!</p>"; } } } else if (($_POST) && ($_POST["action"] == "unsub")) { //trying to unsubscribe; validate email address if ($_POST["email"] == "") { header("Location: manage.php"); exit; } else { //connect to database doDB(); //check that email is in list emailChecker($_POST["email"]); //get number of results and do action if (mysqli_num_rows($check_res) < 1) { //free result mysqli_free_result($check_res); //print failure message $display_block = "<p>Couldn't find your address!</p> <p>No action was taken.</p>"; } else { //get value of ID from result while ($row = mysqli_fetch_array($check_res)) { $id = $row["id"]; } //unsubscribe the address $del_sql = "DELETE FROM subscribers WHERE id = '".$id."'"; $del_res = mysqli_query($mysqli, $del_sql) or die(mysqli_error($mysqli)); $display_block = "<P>You're unsubscribed!</p>"; } mysqli_close($mysqli); } } ?> <html> <head> <title>Subscribe/Unsubscribe to a Mailing List</title> </head> <body> <h1>Subscribe/Unsubscribe to a Mailing List</h1> <?php echo "$display_block"; ?> </body> </html>

Sendmymail.php
<?php if (!$_POST) { //haven't seen the form, so display it echo "<html> <head> <title>Send a Newsletter</title> </head> <body> <h1>Send a Newsletter</h1> <form method=\"post\" action=\"".$_SERVER["PHP_SELF"]."\"> <p><strong>Subject:</strong><br/> <input type=\"text\" name=\"subject\" size=\"30\"></p> <p><strong>Mail Body:</strong><br/> <textarea name=\"message\" cols=\"50\" rows=\"10\" wrap=\"virtual\"></textarea> <p><input type=\"submit\" name=\"submit\" value=\"Send It\"></p> </form> </body> </html>"; } else if ($_POST) { //want to send form, so check for required fields if (($_POST["subject"] == "") || ($_POST["message"] == "")) { header("Location: sendmymail.php"); exit; } //connect to database $mysqli = mysqli_connect("localhost", "root", "", "test"); if (mysqli_connect_errno()) { //if connection fails, stop script execution printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { //otherwise, get emails from subscribers list $sql = "SELECT email FROM subscribers"; $result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli)); //create a From: mailheader $mailheaders = "From: Your Mailing List <you@yourdomain.com>"; //loop through results and send mail while ($row = mysqli_fetch_array($result)) { set_time_limit(0); $email = $row["email"]; mail("$email", stripslashes($_POST["subject"]), stripslashes($_POST["message"]), $mailheaders); echo "newsletter sent to: ".$email."<br/>"; } mysqli_free_result($result); mysqli_close($mysqli); } } ?>

Ivn Martn Valderas

Pgina 6

Lista de Correos
3. Modificacin del fichero php.ini

Cambiamos el php.ini en la ruta C:\xampp\php [mail function] ; For Win32 only. ; http://php.net/smtp SMTP = mail.dispostable.com ; http://php.net/smtp-port smtp_port = 25

; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = autoenviable@dispostable.com

4. Insercin de Datos y comprobacin

Ejecutamos el fichero manage.php y escribimos las direcciones de los suscriptores:

El servidor nos responde:

Insertamos en total 4 direcciones mail: Princee11@hotmail.com Priincee11@gmail.com emailproyect@dispostable.com uncorreo@mail.com

Si el email que queremos suscribir ya se encuentra en la base de datos, el servidor nos devolver un mensaje:

Ivn Martn Valderas

Pgina 8

Lista de Correos
Para comprobar los mails suscritos, vamos a mysql y ejecutamos la sentencia: Select * from subscribers;

El mail uncorreo@mail.com no existe por lo que vamos a eliminarlo desde el archivo php y comprobamos qu mensaje nos muestra:

De la misma manera comprobamos en mysql que se ha dado de baja en nuestra base de datos:

5. Envo de un correo

Ya tenemos en nuestra base de datos a nuestros suscriptores, ahora vamos a mandarles un correo a todos.

Ejecutamos nuestro fichero sendmymail.php:

Al darle a Send It enviaremos el mensaje a todos.

newsletter sent to: emailproyect@dispostable.com newsletter sent to: priincee11@gmail.com newsletter sent to: princee11@hotmail.com

Ivn Martn Valderas

Pgina 10

Lista de Correos
6. Comprobacin de mails correctos
Vamos a cambiar el archivo manage.php para la validacin de correos:
<?php //set up a couple of functions function doDB() { global $mysqli; //connect to server and select database; you may need it $mysqli = mysqli_connect("localhost", "root", "", "mailproyect"); //if connection fails, stop script execution if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } } function comprobar_email($email){ $mail_correcto = 0; //compruebo unas cosas primeras if ((strlen($email) >= 6) && (substr_count($email,"@") == 1) && (substr($email,0,1) != "@") && (substr($email,strlen($email)-1,1) != "@")){ if ((!strstr($email,"'")) && (!strstr($email,"\"")) && (!strstr($email,"\\")) && (!strstr($email,"\$")) && (!strstr($email," "))) { //miro si tiene caracter . if (substr_count($email,".")>= 1){ //obtengo la terminacion del dominio $term_dom = substr(strrchr ($email, '.'),1); //compruebo que la terminacin del dominio sea correcta if (strlen($term_dom)>1 && strlen($term_dom)<5 && (!strstr($term_dom,"@")) ){ //compruebo que lo de antes del dominio sea correcto $antes_dom = substr($email,0,strlen($email) - strlen($term_dom) - 1); $caracter_ult = substr($antes_dom,strlen($antes_dom)-1,1); if ($caracter_ult != "@" && $caracter_ult != "."){ $mail_correcto = 1; } } } } } if ($mail_correcto) return 1; else return 0; } function emailChecker($email) { global $mysqli, $check_res; //check that email is not already in list $check_sql = "SELECT id FROM SUBSCRIBERS WHERE email = '".$email."'";

$check_res = mysqli_query($mysqli, $check_sql) or die(mysqli_error($mysqli)); } //determine if they need to see the form or not if (!$_POST) { //they need to see the form, so create form block $display_block = " <form method=\"POST\" action=\"".$_SERVER["PHP_SELF"]."\"> <p><strong>Your E-Mail Address:</strong><br/> <input type=\"text\" name=\"email\" size=\"40\"> <p><strong>Action:</strong><br/> <input type=\"radio\" name=\"action\" value=\"sub\" checked> subscribe <input type=\"radio\" name=\"action\" value=\"unsub\"> unsubscribe <p><input type=\"submit\" name=\"submit\" value=\"Submit Form\"></p> </form>"; } else if (($_POST) && ($_POST["action"] == "sub")) { //trying to subscribe; validate email address if ($_POST["email"] == "") { header("Location: manage.php"); exit; } else { //connect to database doDB(); //check that email is in list emailChecker($_POST["email"]); //COMPROBAR SI EST BIEN ESCRITO if (comprobar_email($_POST["email"]) == 0) { $display_block = "<p>Error, Intenta insertar un mail correcto</p>"; } else{ //get number of results and do action if (mysqli_num_rows($check_res) < 1) { //free result mysqli_free_result($check_res); //add record $add_sql = "INSERT INTO subscribers (email) VALUES('".$_POST["email"]."')"; $add_res = mysqli_query($mysqli, $add_sql) or die(mysqli_error($mysqli)); $display_block = "<p>Thanks for signing up!</p>"; //close connection to MySQL mysqli_close($mysqli); } else { //print failure message $display_block = "<p>You're already subscribed!</p>"; } }

Ivn Martn Valderas

Pgina 12

Lista de Correos
} } else if (($_POST) && ($_POST["action"] == "unsub")) { //trying to unsubscribe; validate email address if ($_POST["email"] == "") { header("Location: manage.php"); exit; } else { //connect to database doDB(); //check that email is in list emailChecker($_POST["email"]);

//get number of results and do action if (mysqli_num_rows($check_res) < 1) { //free result mysqli_free_result($check_res); //print failure message $display_block = "<p>Couldn't find your address!</p> <p>No action was taken.</p>"; } else { //get value of ID from result while ($row = mysqli_fetch_array($check_res)) { $id = $row["id"]; } //unsubscribe the address $del_sql = "DELETE FROM subscribers WHERE id = '".$id."'"; $del_res = mysqli_query($mysqli, $del_sql) or die(mysqli_error($mysqli)); $display_block = "<P>You're unsubscribed!</p>"; } mysqli_close($mysqli); } } ?> <html> <head> <title>Subscribe/Unsubscribe to a Mailing List</title> </head> <body> <h1>Subscribe/Unsubscribe to a Mailing List</h1> <?php echo "$display_block"; ?> </body> </html>

De esta manera si intentamos insertar mails que no cumplan las condiciones:

El servidor nos responde:

Al igual que si escribimos mal nuestro correo de otras maneras como:

Ivn Martn Valderas

Pgina 14

You might also like