Search code examples
phpphpmailerrecaptcha

PHP + SMTP form + reCaptcha


I'm adding Google reCaptcha to this PHPMailer form.

It should be sent via SMTP.

How should I verificate reCaptcha and send current form? How if statement should be written here?

This my index.html file's code:

<form class="form-subscribe" action="mail.php" method="post">
<div class="container">
<div class="row">
<input type="text" class="form-control col-md-5 form-name" name="name" placeholder="Ваше имя" required>
<div class="col-md-1"></div>
<input type="text" class="form-control col-md-6 form-email" name="email" placeholder="Ваша эл. почта" required>
<textarea type="text" class="form-control form-text bg-gray col-md-12" name="message" placeholder="Ваше сообщение" required></textarea>
</div>
<div class="input-group-append">
<div class="g-recaptcha" data-sitekey=""></div>
<button class="button button-shadow2" type="submit" name="submit">Отправить</button>
</div>
</div>
</form>

This is mail.php file's code:

    <?php 

    require_once('phpmailer/PHPMailerAutoload.php');
    $mail = new PHPMailer;
    $mail->CharSet = 'utf-8';

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '';
    $mail->Password = '';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    $mail->setFrom($email); 
    $mail->addAddress('');
    $mail->isHTML(true);                             

    $mail->Subject = 'Сообщение с сайта';
    $mail->Body    = '' .$name . ' оставил заявку, его телефон ' .$email. '<br>Сообщение этого посетителя: ' .$message;
    $mail->AltBody = '';



 if(!$mail->send()) {
        echo 'Message sent!';
    } else {
        echo 'Error!';
    }
    ?>

Solution

  • It´s not so complicated as it looks, i´ve given you an example in the comments of your question. Now i´ll give you a little walk through.

    Notice: This example was not tested but i´ve made a syntax check.

    enter image description here

    Your html code is okay so there no changes needed.

    As you already know you´ve only to add your key:

    <div class="g-recaptcha" data-sitekey="YOUR_KEY"></div>
    

    Now we will get the "recaptcha data":

    $response = $_POST["g-recaptcha-response"];
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    

    Recptcha needs some data to validate the captcha:

    $data = array(
        'secret' => 'YOUR_SECRET',
        'response' => $_POST["g-recaptcha-response"]
    );
    
    
    
    $options = array(
        'http' => array (
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );
    

    Next the script must get all data and verfiy the captcha, with file_get_contents it will load the recaptcha data and decode it with json:

      $context  = stream_context_create($options);
      $verify = file_get_contents($url, false, $context);
      $captcha_success=json_decode($verify);
    

    At least we need a if loop to check if the captcha is valid or not:

    if ($captcha_success->success==false) {
        echo "false";
    } else if ($captcha_success->success==true) {
        echo "true";
    }
    

    The next step is quick & dirty:

    if ($captcha_success->success==false) {
        echo "Captcha wrong";
    } else if ($captcha_success->success==true) {
    
    if(!$mail->send()) {
        echo 'Message sent!';
    } else {
        echo 'Error!';
    }
    }
    

    So the complete code would look like this:

    require_once('phpmailer/PHPMailerAutoload.php');
    $mail = new PHPMailer;
    $mail->CharSet = 'utf-8';
    
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '';
    $mail->Password = '';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    
    $mail->setFrom($email); 
    $mail->addAddress('');
    $mail->isHTML(true);                             
    
    $mail->Subject = 'Сообщение с сайта';
    $mail->Body    = '' .$name . ' оставил заявку, его телефон ' .$email. '<br>Сообщение этого посетителя: ' .$message;
    $mail->AltBody = '';
    
    $response = $_POST["g-recaptcha-response"];
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $data = array(
        'secret' => 'YOUR_SECRET',
        'response' => $_POST["g-recaptcha-response"]
    );
    $options = array(
        'http' => array (
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $verify = file_get_contents($url, false, $context);
    $captcha_success=json_decode($verify);
    
     if ($captcha_success->success==false) {
        echo "Captcha wrong";
    } else if ($captcha_success->success==true) {
    
    if(!$mail->send()) {
        echo 'Message sent!';
    } else {
        echo 'Error!';
    }
    }
    

    Here is to origial tutorial (json): https://www.kaplankomputing.com/blog/tutorials/recaptcha-php-demo-tutorial/

    This page provides a tutorial with ajax too: https://www.kaplankomputing.com/blog/tutorials/php/setting-recaptcha-2-0-ajax-demotutorial/