Including reCAPTCHA functionality in HTML Form with PHP

edited December 2023 in PHP

  1) Go to https://www.google.com/recaptcha/admin/create  to create Site Key and Secret Key

2) Include the API of reCAPTCHA as <script src="https://www.google.com/recaptcha/api.js?render="your-site-key"></script>

CODE:

3) Now write your HTML form code
<form id="contact-form" method="POST" >


 <input class="form-control" name="email" id="email" type="email" placeholder="Email">


  <input type="hidden" name="g-recaptcha-response" value="" id="g-recaptcha-response">


  <button style="background: #ff9900;" class="submit submit-auto-width" id="con_form" type="submit">Post Comment</button>


</form>


4) Now handle your form submission using javascript as shown


$(document).ready(function() {

        var request;

        $('#contact-form').submit(function(event) {


            var $form = $(this);


            grecaptcha.ready(function() {


                grecaptcha.execute('6LdleTQpAAAAANhBdRecwrL9pqxPrvHXgLA-keKg', {


                    action: 'submit'


                }).then(function(token) {




                    $('#g-recaptcha-response').val(token);




                    var serializeDataArray = $form.serializeArray();




                    var email = document.getElementById("email").value.trim();


                         if (email === "") {


                        displayError("email-error", "Email is required");


                        return;


                    }


                    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;


                    if (!emailRegex.test(email)) {


                        displayError("email-error", "Please enter a valid email address");


                        return;


                    }




                    $.ajax({


                        type: 'POST',


                        url: '/blog_comment',


                        data: serializeDataArray,


                        dataType: 'json',


                        success: function(data) {




                            if (data.error === '0') {


                                document.getElementById("email").value = '';


                                MyToast("Thank you for contacting us!", 'success');


                            } else {


                                MyToast("Something Went Wrong, please try again later!", 'fail');


                            }


                        }


                    });


                });


            });


        });


    });




5) Write a function which can handle the verification of recaptcha response


  function validate_g_recpatcha_response($g_recpatcha_response)

        {

            $post = [


                'secret' => 'your-secret-key',


                'response' => $g_recpatcha_response


            ];


            $ch = curl_init('https://www.google.com/recaptcha/api/siteverify');


            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);


            $response = curl_exec($ch);


            curl_close($ch);


            return json_decode($response, true);


        }

6)Write the backend code for handling the form submission

 public function contact-form()

    {

        $g_recaptcha_validation_det = validate_g_recpatcha_response($_POST["g-recaptcha-response"]);


        if ($g_recaptcha_validation_det["success"] == 1 && $g_recaptcha_validation_det["score"] >= google_recaptcha_accepted_score) {


            if ($_SERVER['REQUEST_METHOD'] === 'POST') {


                extract($_POST);


                $data["mail_id"] = $email;


                $this->common->insert_data('contact', $data);


                $response["error"] = "0";


                $response["message"] = "Added successfully";


            } else {


                $response["error"] = "1";


                $response["message"] = "Please use correct request method...";


            }


        } else {


            $response["error"] = "1";


            $response["message"] = "Recaptcha  failed";


        }

        echo json_encode($response);


    }


Sign In or Register to comment.