Google reCAPTCHA v3, How to use validation of HTML JQuery PHP Form.

Google reCaptcha v3 returns JSON format data. That data based on interactions with your website and validate the form submit inquiries if the submitted form inquiry is validated then it’s sent to the owner or form used scrapping then reCaptcha does not send any details to Owner with does not run the remaining script.

Documentation of Google reCaptcha

https://developers.google.com/recaptcha/docs/v3

 

HTML Code – Input Form

<form action="#" method="post" id="formAction">
<div><input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" /></div> 
<div><input type="text" value="" /></div> 
<div><button id="submitPost">Submit Post</button></div> 
</form>

 

PHP Code – For getting JSON Response

<?php 
define('SITE_KEY', '6Ld82pxxxxxxxxxxxxxxxxxSITExxxxKEYxxxxxxxxxx'); 
define("SECRET_KEY", "6Ld82poUxxxxxxxxSECRETxxxxxKEYxxxxxxxxxx"); 

if($_POST){
function getCaptcha($key){
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".SECRET_KEY."&response={$key}"); 
$return = json_decode($response);
return $return; 
} 

$return = getCaptcha($_POST['g-recaptcha-response']);
// var_dump($return);
if( $return->success == true && $return->score > 0.5){
echo 'Sucess';
$_SESSION["favcolor"] = "send";
}else{
echo 'you are robot';
$_SESSION["favcolor"] = "not-send";
   }
}

?>

 

JavaScript Code – To Getting reCaptcha Token

<script src="https://www.google.com/recaptcha/api.js?render=6Ld82pxxxxxxxxxxxxxxxxxSITExxxxKEYxxxxxxxxxx"></script>
<script>
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6Ld82pxxxxxxxxxxxxxxxxxSITExxxxKEYxxxxxxxxxx', {action:'send_form'})
.then(function(token) {
// add token value to form
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *