Google has a nifty way of checking if you’re human or not.
I wrote a PHP Class for verifying ReCaptcha v.2.
<?php
class asbraRecap
{
public $google_secret_key;
public $google_site_key;
public function include_java()
{
return("
<script> src='https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit' async defer>
<script> type='text/javascript'>
// Change this to your Google site-key
sitekey = '$this->google_site_key'
var onloadCallback = function() {
grecaptcha.render('asbra_recaptcha', {
'sitekey' : sitekey
});
};
");
}
public function verify_recaptcha()
{
// Set some variables
$response = $_POST["g-recaptcha-response"];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => $this->google_secret_key,
'response' => $_POST["g-recaptcha-response"]
);
// Options for file_get_contents()
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
),
/* If in chroot, like me */
"ssl"=>array(
"cafile" => "/cacert.pem",
"verify_peer"=> true,
"verify_peer_name"=> true
)
);
// Talk to Google
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify, true);
// Is Captcha successfull ?
if ( false == $captcha_success['success'])
{
// Prepare array to return
$return['status'] = false;
// Save errors from Google in array
foreach ( $captcha_success['error-codes'] as $key => $val ) {
$return['errors'][] = $val;
}
// Return our array
return $return;
}
elseif ( true == $captcha_success['success'])
{
// Prepare array to return
$return['status'] = true;
$return['hostname'] = $captcha_success['hostname'];
$return['challenge_ts'] = $captcha_success['challenge_ts'];
return $return;
}
// If all else fails
return false;
}
}And some HTML
<html>
<head><title>DEMO - ReCaptcha PHP Class - ASBRA AB</title></head>
<body>
<?php // Initiate a New Class Object
require_once('asbra-class-recap.php');
$asbraRecap = new asbraRecap();
$asbraRecap->google_secret_key = '6Led02MUAAAAAGqsXPr1sx5xZGFKf8Oj3-EVL-lP';
$asbraRecap->google_site_key = '6Led02MUAAAAACweP4BxEIFP_UR011tItvXm3BoT';
?>
<?php // If Captcha is Posted & Verified
if(isset($_POST["g-recaptcha-response"])) : if ($result = $asbraRecap->verify_recaptcha()) : if ($result['status'] == true) : ?>
<h2>En Människa Verifierad!</h2>
<?php else : ?>
<h2>Verifiering av en människa misslyckades</h2>
<?php endif; endif; endif; ?>
<form method="POST">
<div id="asbra_recaptcha"></div> <br>
<input type="submit" value="Submit">
</form>
<?php // need som java
echo $asbraRecap->include_java(); ?>
</body>
</html>
The End!
