Registration confirmation email

2

I made a cpf and email address. I've already put it to validate cpf and such, and I can send the email to the user who put the email there, but I need the registration to be done only if the email actually exists. In the case, would I have to do a single email confirmation of registration for when he clicked there, validate the registration, or would have some easier way? Because when I send the email to some nonexistent, it even confirms the registration and is placed in the bd. And how do I do this?

The code to send email:

    <?php

    require_once 'PHPMailer/PHPMailerAutoload.php';


   $mail = new PHPMailer();
   $mail->IsSMTP();
   $mail->Host = 'host aqui';
   $mail->Port = 587;
   $mail->SMTPAuth = true;
   $mail->IsHTML(true);
   $mail->Username = 'emailr';
   $mail->Password = 'senha';

   $mail->SMTPSecure = false; //Diz que nao tem tls/ssl
   $mail->SMTPAutoTLS = false; //Diz que nao tem tls/ssl

   $mail->SMTPDebug = 2; //Mostra os bugs


    //E-mail remetente (deve ser igual ao que esta enviando)
    $mail->From = 'email';

    //Nome do remetente
    $mail->FromName ='Lojas';

    //Assunto da mensagem
    $mail->Subject = 'Texto';

    //Corpo da mensagem
    $mail->Body = 'Ola';

    //Corpo da mensagem em texto
    $mail->AltBody = 'Conteudo do e-mail em texto';

    //Destinatario 
    $mail->AddAddress ('exemplo@email');

    if ($mail->Send()) {
        echo "e-mail enviado com sucesso";
       echo'<script> alert("Cadastro realizado com sucesso!")</script>';
    }else{
        echo "Erro no envio do e-mail" .$mail->ErrorInfo;
    }

?>

Registration code:

                    <label >CPF*:</label>
                    <input type="text" id="cpf" name="cpf" title="Digite o CPF no formato nnn.nnn.nnn-nn" class="form-control input-lg" placeholder="000.000.000-00" maxlength="14" required /><span id="resposta"></span>

  <br>
                    <label inputemail>E-mail*:</label>
                    <input type="email" id="email" name="email" class="form-control input-lg email" placeholder="[email protected]" maxlength="50" required />

                      <br>
  <br>

                    <button type="submit" class="btn btn-primary btn-lg btn-block" id="cadastrar" name="cadastrar" disbled/ >
                        <span class="glyphicon glyphicon-ok"></span>
                        <span id="cpf"></span>Cadastrar</button>

ValidaCadastro screen:

<?php
// ini_set('display_errors', '1');
ini_set('display_errors',1);
ini_set('display_startup_erros',1);

?>
<?php

require_once "config/conexao.php";

  $var1 = $_POST['cpf'];
  $var2 = $_POST['email'];

  $query = "SELECT * FROM teste WHERE email = '$var2'";
  $query = "SELECT * FROM teste WHERE cpf = '$var1'";


      $querySelect = mysqli_query($conn, $query);

        if (mysqli_num_rows($querySelect) > 0) {
          echo"<script type='text/javascript'>alert('Cadastro existente.');window.location.href='cadastro.php';</script>";
        }

        $var1 = $_POST['cpf'];
        $var2 = $_POST['email'];



            if ($mail->Send()) {
                echo "e-mail enviado com sucesso";
               echo'<script> alert("Cadastro realizado com sucesso!")</script>';

            if(!$stmt){
              echo 'erro na consulta: '. $conn->error .' - '. $conn->error;
            }



            }else{
                echo "Erro no envio do e-mail" .$mail->ErrorInfo;
            }
    
asked by anonymous 04.12.2017 / 13:41

2 answers

3

Schematization of validation of registration through a validation link

I would recommend having a unique user code column for each user, at least 8 characters (letters and numbers). This code must be randomly generated by some code generator or you can get the current date (year, month, day, hour, minute, and seconds, getting something like this: 20171204134422 ). If you do not want this, you can use id of the user in the same bank, if there is no problem of knowing this information.

1st. The user signs up on the site. The registration is inactive and a confirmation email is sent with the link to validate the registration. The link would look something like this:

link

Example of what the message sent to the user would look like:

  

Hello! Welcome to the site!

     

Click the following link to confirm your registration:    link

The message body code you would mount this way:

<?php
$corpo = '
Olá! Bem-vindo ao site!
<br /><br />
Clique no link a seguir para confirmar seu cadastro:
<br />
<a href="http://nome_do_site.com.br/validar.php?email='.$email_usuario.'&codigo='.$codigo.'" target="_blank">http://nome_do_site.com.br/validar.php?email='.$email_usuario.'&codigo='.$codigo.'</a>
';

$mail->Body = $corpo;
?>

2nd Create a file on your site validar.php (example) to receive and treat the email and codigo received in the link, verifying that the two coincide in the same register, validating whether or not there is validation in case of any divergence.

This is just a simple example just to illustrate the process.

In terms of programming the whole process (inclusion of the database in the database, validation and activation) are other issues, and if you do not know how to do it, you can search the site and find out how.

    
04.12.2017 / 14:38
0

To avoid inserting an email in the database that does not exist and in the future has to be deleted, you can do so.

Comments in the code

Form and Email on same page

<?php
if(isset($_POST['cpf']) && isset($_POST['email'])){     
    require_once 'PHPMailer/PHPMailerAutoload.php';

   $mail = new PHPMailer();
   $mail->IsSMTP();
   $mail->Host = 'host aqui';
   $mail->Port = 587;
   $mail->SMTPAuth = true;
   $mail->IsHTML(true);
   $mail->Username = 'emailr';
   $mail->Password = 'senha';

   $mail->SMTPSecure = false; //Diz que nao tem tls/ssl
   $mail->SMTPAutoTLS = false; //Diz que nao tem tls/ssl

   $mail->SMTPDebug = 2; //Mostra os bugs

   //recupera via post valor do cpf
   $cpf = Trim(str_replace("'","",$_POST["cpf"]));
   //cookie cujo valor é o cpf com duração de 2 dias
   setcookie("cpf",$cpf,time()+(2*86400),"/");

   //email para usar no corpo da mensagem e em Destinatario
   $e_mail = $_POST["email"];
   $e_mail = Trim(str_replace("'","",$e_mail));


    //E-mail remetente (deve ser igual ao que esta enviando)
    $mail->From = 'email';

    //Nome do remetente
    $mail->FromName ='Lojas';

    //Assunto da mensagem
    $mail->Subject = 'Texto';

    //Corpo da mensagem
    $mail->Body = "Ola, Clique <a href='http://dominio.com/validaCadastro.php?mail=".$e_mail."'>aqui</a> para ativar seu cadastro.";

    //Corpo da mensagem em texto
    $mail->AltBody = 'Conteudo do e-mail em texto';


    //Destinatario 
    $mail->AddAddress ($e_mail);

    if ($mail->Send()) {
        echo "e-mail enviado com sucesso";
       echo'<script> alert("Cadastro realizado com sucesso!")</script>';
    }else{
        echo "Erro no envio do e-mail" .$mail->ErrorInfo;
    }
}
?>

<form class="form" id="form1" method="POST" action="">

<label >CPF*:</label>
<input type="text" id="cpf" name="cpf" title="Digite o CPF no formato nnn.nnn.nnn-nn" class="form-control input-lg" placeholder="000.000.000-00" maxlength="14" required /><span id="resposta"></span>
<br>
 <label inputemail>E-mail*:</label>
 <input type="email" id="email" name="email" class="form-control input-lg email" placeholder="[email protected]" maxlength="50" required />

<br>
<br>

 <button type="submit" class="btn btn-primary btn-lg btn-block" id="cadastrar" name="cadastrar" disbled/ >
 <span class="glyphicon glyphicon-ok"></span>
 <span id="cpf"></span>Cadastrar</button>

 </form>

Page that inserts into database validaCadastro.php

if ($_GET["mail"] != "") {

 $mysqli = new mysqli("localhost", "USUARIO", "SENHA", "NOME_DB");

 //recupera valor do cookie
 $cpf = $_COOKIE['cpf'];
 $getMail= $_GET["mail"];

 $result = $mysqli->query("SELECT COUNT(*) FROM tabela WHERE email = '$getMail'");

        $row = $result->fetch_row();
        if ($row[0] > 0) {
             $alerta =("E-mail (".$getMail.") já existente.");
        } else {
            $mysqli->query("Insert into tabela (email,cpf) values ('".$getMail."','".$cpf."')");
        }


}

Considering the comments of Guilherme Nascimento :

  

"I do not believe cookies are a good way, the way you applied may be something that does not work, especially if the user eventually can not confirm the email on the same machine that registered, depending on whether the validateCadastro .php? mail=". $ e_mail." 'doing autologon could be a huge security hole, "

The best solution is to answer the ÐvÐ!

    
04.12.2017 / 15:13