Email confirmation of registration

Asked

Viewed 2,825 times

2

I signed up with Cpf and email. I already put 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 really exists. In this case, I would have to make a single email confirmation of registration for when he click there, validate the registration, or would have some easier way? Because when I send the email to some non-existent one, it still 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>

Screen of validationCadastro:

<?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;
            }
  • The registration must exist anyway, the confirmation email is just to confirm. What you can do is only release the access after the email is confirmed.

  • So...I put an email that does not exist, and even then the registration is successfully done. And I know that the email does not exist because I have checked it

  • it’s just Cpf and email?

  • Yes. I put Cpf as PK, and I checked Cpf to see if it exists or not. Now I have to validate the email, to know if it exists or not

  • I think of two solutions: first send to the registration email ->> Clique <a href='http://dominio.com/ativar.php?cpf=".$cpf."&email=".$email."'>aqui</a> para ativar seu cadastro. Dai vc take these values and make Insert in the bank

  • But how exactly do I do that? You can give an example?

  • What is your difficulty? Email the user with this line?

  • I can send email to the customer, what I do not know is send an email with confirmation link, in case he receives the email, have to click the link, then when click the email goes to bd

  • have to put exactly this line in the body of the email message

  • I wouldn’t advise sending the CPF on the validation link. Since it is a confidential data, it would be better to have in the bank a column with a unique code for each user of some 8 characters (letters and numbers), then creates the validation link using this code + email.

  • @Yes, but how exactly do I do that?

  • @In the content of the message will not show any Cpf data

  • @The extra job to clean bank with unreturned, if you do not want to expose Cpf in link make use of localStorage which would be the second solution

  • Put your email code in the question

  • @Leocaracciolo ready

  • If any answer has solved your question, be sure to mark it as accepted, see how and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

Show 11 more comments

2 answers

2


Registry validation schematics through a validation link

I would recommend having in the table user registration a single code column for each user, at least 8 characters (letters and numbers). This code should be generated randomly by some code generator or you can pick up the current date (year, month, day, hour, minutes and seconds, more or less like this: 20171204134422). If you don’t want this, you can use the id user in the same bank, if there is no problem it know this information.

first. The user registers on the site. The registration is inactive and a confirmation email is sent with the link to validate the registration. The link would be something like this:

http://nam_do_site.com.br/[email protected]&codigo=sh35j87k

Example of how the message sent to the user would look:

Hello! Welcome to the website!

Click on the following link to confirm your registration: http://nam_do_site.com.br/[email protected]&codigo=sh35j87k

The body code of the message you would mount in 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 website validar.php (example) to receive and treat email and the codigo received in the link, checking if the two coincide in the same register, validating if there are or not validating if there is some divergence.

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

Regarding the programming of the whole process (inclusion of the registration in the database, validation and activation) are other issues, and if you do not have the knowledge to do them, you can search the site and find how to do.

  • 2

    They did not like your reply and did not comment, because they do not comment?

  • @Leocaracciolo No problem. Even tried to give an improved. I gave the path of the stones, programming the AP should at least know.

  • There is nothing wrong with your answer, in fact I think your solution is the right way to go. I just don’t understand these people who put on a "-" and leave no comment on what’s wrong.

  • @lazyFox Because eh. The -1 would be for when the answer is not useful. In case, I think my answer is useful, only it does not serve as a whole system working.

  • I think it’s a good technical response, explaining the step by step, I can’t say it will solve the PA problem, but I personally think it’s the most ideal, especially since it cares about security at the time of confirmation, still as a suggestion, random code could be a slightly more complicated hash, dates, times, and the like may not be a guaranteed method. + 1 mainly indicating safety concern.

0

To avoid entering into the bank an email that does not exist and in the future have to delete, you can do so.

Comments on the code

Form and Send email on the 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 you enter in the 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 don’t think that cookies is a good way, the way you applied it can be something that doesn’t work, even more so if the user eventually can’t confirm the email on the same machine that registered, other than depending on the validatCadastro.php? mail=". $e_mail." 'autologon may be a major security breach,"

the best solution is that of the answer of the!

  • I didn’t quite understand your code. This email and Cpf data will have to be picked up by the registration page, right? I will update the codes in the question

  • yes, the registration page submits the form to the email page

  • Can you take a look at the codes I’ve put in now? Then...validaCadastro will be replaced by activating.php?

  • Exactly the validatCadastro will be replaced by activating.php, The registration sends to the email sending page (which may be the same page). The page activate (when the user clicks on the received link) checks if the email already exists in the bank, if there is no insert

  • But that’s not what I want. I need to check if the email really exists, in gmail, outlook etc.

  • You will only know if the email really exists if the user gives feedback, otherwise you should have a table with all the valid emails from the whole world for you to take the test!!

  • I think I get it... but it keeps giving syntax error in: $result = $mysqli->query("SELECT COUNT(*) FROM tabela WHERE email = '$_GET["mail"]'");

  • @Nazarelisboa, my inattention, corrected and edited the answer.

  • The email is sent to me and such, but it gives this error: Undefined index: mail in C: xampp htdocs testaOficial activates.php on line 3 : if ($_GET["mail"] != "")

  • And it keeps giving Cpf error, as if it had not found: Undefined index: Cpf in ...

  • It keeps saying the same thing, and when I click on the link that came to my email, it shows this: Uncaught Error: Call to a Member Function fetch_row() on Boolean in C: xampp htdocs...

  • Beauty. I wait

  • on the form page change to if(isset($_POST['cpf']) && isset($_POST['email'])){ I tested and it worked on my server

  • Now when I click on the link that was sent to my email, I get this error: Fatal error: Uncaught Error: Call to a Member Function fetch_row() on Boolean in C: xampp htdocs test validaCadastro.php:12 Stack trace: #0 {main thrown} in C: xampp htdocs test validaCadastro.php on line 12

  • 1

    Just citing the points that I find problematic in the answer: I do not believe that cookies is a good way, the way that applied may be something that does not work, even more if the user eventually can not confirm the email on the same machine that was signed up, besides that depending on the validaCadastro.php?mail=".$e_mail."' Doing the autologon could be a major security breach, the answer from Yivý suggests a validation code, which I think could be an idea for you to implement in your code. (cc @Nazarelisboa)

  • @Guilhermenascimento, from what I understand she doesn’t want to enter in the non-existent email bank Então...eu coloco um email que não existe, e mesmo assim o cadastro é efetuado com sucesso. However, activate registration is another situation not discussed in the question.

Show 11 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.