Google reCAPTCHA is one of the best way to protect website from bots. Currently google provides V2 and V3 of reCAPTCHA. In this tutorial we are going to Integrate Google reCAPTCHA v3 in PHP. I am going to use Ajax form submit in my example.
Before jumping into the coding let see how reCAPTCHA v3 works.
In simple words, Google reCAPTCHA v3 is a javascript API which returns score on the basis of user interaction. It won’t show any image or code to fill in.
Get reCAPTCHA site key and secret key.
First of all you need to get site key and secret key for Google reCAPTCHA v3.
- Site key will use in front end to get reCAPTCHA response
- Secret key will use in backend to validate the response from reCAPTCHA.
For local testing use localhost as domain
Integrate Google reCAPTCHA v3 example in PHP
I will be using simple HTML form with 2 fields only.
Form HTML:
Below is the simple html form with 2 fields only. Also there is a hidden input type which will use in google response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<div class="container"> <h1>Message Form:</h1> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" id="postForm"> <div> <input type="text" name="subject" placeholder="subject" id="subject"> </div> <div> <textarea name="message" placeholder="Type your message" id="message"></textarea> </div> <div> <input type="hidden" name="google_response" value="" id="googleResponse"> <button type="submit" name="submit">Submit</button> <div id="response"></div> </div> </form> </div> |
Javascript Code:
First of all I include Google reCAPTCHA script and pass my site key as render
value. Then on form submit I invoke grecaptcha.ready
function and under grecaptcha.ready
I call grecaptcha.execute
function which takes site key as first parameter and object as second parameter. In object parameter I pass action as a key with submit as a value. After getting the token
, I will put that token value into hidden field and then I will trigger jquery ajax function to post the form response to ajax_response.php
file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<script src="https://www.google.com/recaptcha/api.js?render=<YOUR_SITE_KEY>"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script> $('#postForm').submit(function(e) { e.preventDefault(); grecaptcha.ready(function () { grecaptcha.execute('<YOUR_SITE_KEY>', { action: 'submit' }).then(function (token) { $("#googleResponse").val(token); $.ajax({ url: 'ajax_response.php', type: 'post', data: $('#postForm').serialize(), dataType: 'json', success: function(data){ if(data.response == 'success') { $("#response").css('border','1px solid green'); $("#response").text(data.msg); $("#subject").val(''); $("#message").val(''); } else { $("#response").css('border','1px solid red'); $("#response").text(data.msg); } } }); }); }); }); </script> |
Ajax Response:
At the top of the file I have created a custom php functiongetData()
which will trigger cURL get request. Then I am checking subject and message must have values. If any one of two come with empty value, I will return error response. $urlGoogleCaptcha
holds google url. $recaptchaResonse
calls getData()
function with $urlGoogleCaptcha
and $dataArray
. $dataArray
is an array having recaptcha secret key and google verfication response. $recaptchaResonse
holds the google response in array (google returns response in json format getData() function convert json response into an array).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
<?php function getData($url,$dataArray) { $ch = curl_init(); $data = http_build_query($dataArray); $getUrl = $url."?".$data; curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $getUrl); curl_setopt($ch, CURLOPT_TIMEOUT, 80); $response = curl_exec($ch); if(curl_error($ch)){ return 'Request Error:' . curl_error($ch); } else { return json_decode($response,true); } curl_close($ch); } if(isset($_POST['subject'],$_POST['message'],$_POST['google_response'])) { if(empty($_POST['subject']) || empty($_POST['message'])) { //success response echo json_encode(['response' => 'error','msg'=>'Both fields are required']); exit(); } $urlGoogleCaptcha = 'https://www.google.com/recaptcha/api/siteverify'; $recaptchaSecretKey = '<YOUR_SECRET_KEY>'; $verficationResponse = $_POST['google_response']; $dataArray = [ 'secret'=>$recaptchaSecretKey, 'response'=>$verficationResponse ]; $recaptchaResonse = getData($urlGoogleCaptcha,$dataArray); if(is_array($recaptchaResonse)) { if($recaptchaResonse['success'] == 1) { $subject = trim($_POST['subject']); $message = trim($_POST['message']); //success response echo json_encode(['response' => 'success','msg'=>'Your form has been submitted successfully']); exit(); } else { //google returns false; echo json_encode(['response'=>'error','msg'=>'Google reCaptcha Error']); exit(); } } else { //issue in curl request echo json_encode(['response'=>'error','msg'=>'Error with google']); exit(); } } ?> |