Invisible Recaptcha V3 PHP Example
Complete HTML, JS and PHP Sample on How to get Started with Google Recaptcha V3. The New and Improved Recaptcha V3.
This is a short Recaptcha V3 Example on PHP.
Add this on Your Header Before closing </head>
<script src="https://www.google.com/recaptcha/api.js?render=siteKeyCode"></script>
<script>
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('siteKeyCode', {action:'validate_captcha'})
.then(function(token) {
// add token value to form
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
On your HTML Form add the following snippets
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"> <input type="hidden" name="action" value="validate_captcha">
On Your Server Side Us the Following Code:
$captcha = $_POST['g-recaptcha-response'];
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "XXXXXXXXX";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array('secret' => $secretKey, 'response' => $captcha);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencodedrn",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$responseKeys = json_decode($response,true);
if($responseKeys["success"]) {
//success
} else {
/error
echo "Go Away Bot!";
}