PHP and Google reCaptcha Implementation via cURL

, , ,

So the first step is to add the recaptcha api call to before the close head tag.

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

Then within the form itself before the submit button or where ever you would like the reCaptcha Checkbox to show.

<div class="g-recaptcha" data-sitekey="GOOGLE_SITE_KEY"></div>

The because I use PHP I found the best way to do the checking within the form processing is to use curl.

$data = array(
	'secret' => GOOGLE_SECRET_KEY,
	'response' => $_POST["g-recaptcha-response"]
);

$fields_string = '';
foreach($data as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

$url="https://www.google.com/recaptcha/api/siteverify";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
$captcha_success=json_decode($result);
curl_close($ch);

if ($captcha_success->success==false) {
	$error = true;
	$captchaerror = "Please confirm the captcha.";
}

In the above example GOOGLE_SITE_KEY and GOOGLE_SECRET_KEY need to be replaced for the keys for your domain.  At the bottom where it is checking if the success is false is where I am saying there was an error and also setting the captcha error message that will be displayed.

Skills

Posted on

October 19, 2018

Submit a Comment

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