index.html
<html>
<head>
<title>Google recapcha v3 ajax demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?render=******YOUR-SITE-KEY******"></script>
</head>
<body>
<form id="form_id" method="post" action="form.php">
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
<input type="hidden" name="action" value="contact">
<!--.... your fields-->
</form>
<script src="script.js"></script>
</body>
</html>
script.js
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('******YOUR-SITE-KEY******', {action:'validate_captcha'})
.then(function(token) {
// add token value to form
document.getElementById('g-recaptcha-response').value = token;
});
});
form.php
<?php
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
} else {
$captcha = false;
}
if (!$captcha) {
//Do something with error
} else {
$secret = '******YOUR-SECRET-KEY******';
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
);
// use json_decode to extract json response
$response = json_decode($response);
if ($response->success === false) {
//Do something with error
}
}
//... The Captcha is valid you can continue with the rest of your code
//... Add code to filter access using $response . score
if ($response->success==true && $response->score <= 0.5) {
//Do something to denied access
}
?>