0

So I am trying to use the recaptcha v2 where I have completed the client side part of putting the captcha but the another of server side validation gives an error where the form is submitted but the message shows that "Please click on the reCAPTCHA box." whereas the button is been clicked & also the mail part is not working. I know there is some issue with the JS code to take the POST value of recaptcha in PHP page but could not work on it.. Can anyone help me with it? I have Attached the HTML, JS & PHP code below....

HTML

<form class="comment-one__form contact-form-validated" novalidate="novalidate">
    <div id="success" class="alert alert-success"></div>
    <div class="row">
        <div class="col-xl-6">
            <div class="comment-form__input-box">
                <input type="text" placeholder="Your name" name="name" id="name">
            </div>
        </div>
        <div class="col-xl-6">
            <div class="comment-form__input-box">
                <input type="email" placeholder="Email address" name="email" id="email">
            </div>
        </div>
        <div class="col-xl-6">
            <div class="comment-form__input-box">
                <input type="text" placeholder="Phone number" name="phone" id="phone">
            </div>
        </div>
        <div class="col-xl-6">
            <div class="comment-form__input-box">
                <input type="text" placeholder="Subject" name="subject" id="subject">
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-xl-12">
            <div class="comment-form__input-box text-message-box">
                <textarea name="message" id="message" placeholder="Write comment"></textarea>
            </div>
            <div class="comment-form__btn-box">
                <div class="g-recaptcha" id="gcaptcha" data-sitekey="SITE KEY"></div>
                <button type="submit" id="csubmit" class="thm-btn comment-form__btn">Send a 
                    message</button>
            </div>
        </div>
    </div>
</form>

JS

if ($(".contact-form-validated").length) {
    $(".contact-form-validated").validate({
        // initialize the plugin
        rules: {
        name: {
            required: true
        },
        email: {
            required: true,
            email: true
        },
        phone: {
            required: true,
            digits: true,
            minlength: 10,
            maxlength: 10,
        },
        message: {
            required: true
        },
        subject: {
            required: true
        }
        },
        messages: {
        name: {
            required: "Please enter your name",
        },
        email: {
            required: "Please enter your email",
            email: "Please enter vaild email",
        },
        phone: {
            required: "Please enter your number",
            digits: "Please enter only numbers",
            minlength: "The phone number cannot be less than 10 digits",
            maxlength: "The phone number cannot be more than 10 digits",
        },
        message: {
            required: "Please enter your message",
        },
        },
        submitHandler: function (form) {
        // sending value with ajax request
        $('#csubmit').html('Sending...');
        var user_name = $("#name").val();
        var user_email = $("#email").val();
        var user_phone = $("#phone").val();
        var user_subject = $("#subject").val();
        var user_message = $("#message").val();
        var gcaptcha = $(".g-recaptcha").val();
    
        var formDatanew = new FormData();
        formDatanew.append("name", user_name);
        formDatanew.append("email", user_email);
        formDatanew.append("phone", user_phone);
        formDatanew.append("subject", user_subject);
        formDatanew.append("message", user_message);
        formDatanew.append("g-recaptcha-response", gcaptcha);
        $.ajax({
            url: 'vendor/process.php',
            type: "POST",
            data: formDatanew,
            contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
            processData: false,
            success: function (data) {
            $("form").trigger("reset");
            $('#csubmit').html('Send Message'); 
            $('#success').fadeIn().html(data);  
                setTimeout(function(){  
                $('#success').fadeOut("Slow");  
            }, 5000);
            }
        });
        return false;
        }
    });
    }

PHP

<?php 
    
    
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception; 
    
require '../PHPMailer/src/Exception.php';
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';
    
if(isset($_POST['name']))
{
    $name = addslashes($_POST['name']);
    $email= addslashes($_POST['email']); 
    $contact = addslashes($_POST['phone']);
    $subject = addslashes($_POST['subject']);
    $message = addslashes($_POST['message']);
    
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
    
    // Your Google reCAPTCHA generated Secret Key here
    $secret = 'SECRET KEY';
    
    $serverError = '';
        
    if( ini_get('allow_url_fopen') ) {
        //reCAPTCHA - Using file_get_contents()
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);
    } else if( function_exists('curl_version') ) {
        // reCAPTCHA - Using CURL
        $fields = array(
            'secret'    =>  $secret,
            'response'  =>  $_POST['g-recaptcha-response'],
            'remoteip'  =>  $_SERVER['REMOTE_ADDR']
        );
    
        $verifyResponse = curl_init("https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($verifyResponse, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($verifyResponse, CURLOPT_TIMEOUT, 15);
        curl_setopt($verifyResponse, CURLOPT_POSTFIELDS, http_build_query($fields));
        $responseData = json_decode(curl_exec($verifyResponse));
        curl_close($verifyResponse);
    } else {
        $arrResult = array ('response'=>'error','errorMessage'=>'You need CURL or file_get_contents() activated in your server. Please contact your host to activate.');
        $serverError = true;
    }
    
    if(empty($serverError)) {
    
        if($responseData->success) {
    
            $mail = new PHPMailer;
            $mail->IsSMTP();
            $mail->SMTPDebug = 0;
            $mail->Mailer = "smtp";
            $mail->Host = "smtp.gmail.com";   /*SMTP server*/
            $mail->SMTPAuth = true; 
            $mail->SMTPSecure = "ssl";
            $mail->Port = 465;
            $mail->Username = "*****";  /*Username*/
            $mail->Password = "*****";    /**Password**/
            $mail->isHTML(true);
            $mail->FromName = $name;
            $mail->addReplyTo($email, $name);
            $mail->Body = $body;
            $mail->From = $email; 
            $mail->Subject = "Contact Form";
            $mail->AddAddress("[email protected]");
    
            if($mail->Send()){
    
            echo "Thank you! We will get back to you soon.";
            }
            else{
            echo "Oops! Something went wrong.";
            }
    
        } else {
        echo "Robot verification failed, please try again";
        }
    }
    
    } else { 
    echo "Please click on the reCAPTCHA box.";
    }
    
    }
    
    ?>
5
  • 1
    This doesn't really have anything to do with PHPMailer, but in your PHPMailer code you're forging the from address, which will likely lead to delivery failures. Base your code on the JS contact form example provided with PHPMailer. Those addslashes calls are the wrong kind of sanitisation to use in this context; prefer validation instead.
    – Synchro
    Commented Apr 20, 2022 at 11:40
  • 1
    debug the value of $verifyResponse Commented Apr 20, 2022 at 11:40
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a minimal reproducible example.
    – Community Bot
    Commented Apr 20, 2022 at 16:43
  • @LawrenceCherone Hi checked the value of $verifyResponse, the g-recaptcha-response shows blank in the payload tab of the chrome console while all the other fields like name, email, phone, etc are displayed, also after submission the response message is "Please click on the reCAPTCHA box." Commented Apr 21, 2022 at 5:41
  • @Synchro, I know that this has nothing to do with the PHPmailer because using this code without the Recaptcha code works completely fine & the mails are sent successfully. The only problem is when I try to use the recaptcha the code isn't working. Commented Apr 21, 2022 at 5:43

0

Browse other questions tagged or ask your own question.