Friday, October 27, 2017

How to Google re-captcha client and server validation [SOLVED]

Hey Guys ,

I have integrated the validation of google re captcha in form with server side and client validation . you can learn from here , how we can use in simple web form .

Please follow the below step to achieved google re-captcha  robot integration Api
Create a index.php form page
Step 1 : in you index.php form page include the js file
                         <script src='jquery-ui.js'></script>
                         <script src='https://www.google.com/recaptcha/api.js'></script>
Step 2 : for client side validation include below js
                       <script type="text/javascript" src="jquery.validate.min.js"></script>
Step 3: add below code to render the google robot captcha

<!-- Recaptcha -->
<form class="form-validate" name="frmAdd" id="frmAdd" method="post" enctype="multipart/form-data">
<div class="form-group frm-grp">
<div class="controls">
<div class="g-recaptcha" id="rcaptcha" data-sitekey="XXXXXXXXXXXXXXXXXX"></div>
<input type="hidden" class="hiddenRecaptcha" name="hiddenRecaptcha" id="hiddenRecaptcha">
<?php echo (isset($this->errorMsg['captcha_code_error'])) ? '<label for="hiddenRecaptcha" generated="true" class="error">' . $this->errorMsg['captcha_code_error'] . '</label>' : ''; ?>
</div>
</div>
</form>
<!-- Recaptcha -->

Step 4: validation in client side js inline or separate the below code

jQuery("#frmAdd").validate({
ignore:":disabled",
ignore: ".ignore",
errorElement: 'label',
   rules: {
hiddenRecaptcha:{
required: function() {
if(grecaptcha.getResponse() == ''){
return true;
}else{
return false;
}
  }
}

            },          
            messages: {            
             
hiddenRecaptcha:{
  required: "Please select captcha."
}              
                         
            },
            submitHandler: function (form){
form.submit();
            }
        });

Step 4: check server side as well if CSFR submit from like validation.php include the file in index.php

$captcha_code = JRequest::getVar('g-recaptcha-response');
$secret = 'XXXXXXXXXXXXXXXXXX'; //live
$responseUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha_code;
$verifyResponse = file_get_contents($responseUrl, false);
$responseData = json_decode($verifyResponse);
if (empty($responseData->success)) {
     $validatesmg['captcha_code_error'] = " Please select captcha.";
}

Hopefully you can done all those things to google re-captcha, Please let me know if any difficulty on this. 


No comments:

Post a Comment