Google reCaptcha V2 & V3 javascript demo and php example code

<?php

// google recaptcha v2

$siteKey = 'siteKey222';

$secret = 'secret2222';

// google recaptcha v3

$siteKey_v3 = 'siteKey333';

$secret_v3 = 'secret3333';

function getRrecaptchaResult($secret_key, $g_recaptcha_response)

{

$curl = curl_init();

curl_setopt_array($curl, [

CURLOPT_RETURNTRANSFER => true,

CURLOPT_POST => true,

CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',

CURLOPT_POSTFIELDS => [

'secret' => $secret_key,

'response' => $g_recaptcha_response,

'remoteip' => $_SERVER['REMOTE_ADDR']

]

]);

$response = json_decode(curl_exec($curl));

curl_close($curl);

return$response;

}

if (isset($_POST['g-recaptcha-response'])) {

if (isset($_REQUEST['v3'])) {

$secret = $secret_v3;

}

$captcha = $_POST['g-recaptcha-response'];

if (!$captcha) {

echo'<h2>Please check the the captcha form.</h2>';

exit;

}

$response = getRrecaptchaResult($secret, $captcha);

var_dump($response);

if (!$response || $response->success == false) {

echo'<h2>You are spammer ! </h2>';

} else {

echo'<h2>Thanks for posting comment.</h2>';

}

}

?>

<!DOCTYPE html>

<html lang="en">

<meta charset="UTF-8">

<title>reCAPTCHA demo with php code example</title>

<body>

<?phpif (isset($_REQUEST['v3'])) : ?>

<script src='https://www.google.com/recaptcha/api.js?render=<?php echo $siteKey_v3; ?>'></script>

<form method="POST" name="main_form">

<H1>GOOGLE recaptcha V3, <ahref="?v2=yes">Switch to V2</a></H1>

UserName: <input name="username" />

Address: <input name="address" />

Email: <input name="email" />

v3: <input name="v3" value='v3333'/>

g-recaptcha-response:<input name="g-recaptcha-response" id="g_recaptcha_response" />

<script>

grecaptcha.ready(function() {

grecaptcha.execute('<?phpecho$siteKey_v3; ?>', {action:'action_name'})

.then(function(token) {

document.getElementById('g_recaptcha_response').value = token;

});

});

</script>

<br/><br/>

<inputtype="submit">

</form>

<?php else : ?>

<scriptsrc='https://www.google.com/recaptcha/api.js'></script>

<formmethod="POST">

<H1>GOOGLE recaptcha V2, <ahref="?v3=yes">Switch to V3</a></H1>

UserName: <input name="username" />

Address: <input name="address" />

Email: <input name="email" />

<divclass="g-recaptcha"data-sitekey="<?phpecho$siteKey; ?>"></div>

<br/><br/>

<inputtype="submit">

</form>

<?php endif ?>

<?php

var_dump($_REQUEST);

?>

</body>

</html>

Leave a Reply

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