Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nisdis/c50064dd5e82827849b2ef5cfebb74a6 to your computer and use it in GitHub Desktop.
Save nisdis/c50064dd5e82827849b2ef5cfebb74a6 to your computer and use it in GitHub Desktop.
PHP Verification Function for Google recaptcha Server side code
<?php
/*
* Verifies if the captcha data via Google and redirects to the form page if the captcha does not pass.
* Great for custom contact forms.
*
* Important! : this function requires php-curl or php5-curl library
* Parameters:
* Gcaptcha response - the form data submitted with the request.
** Example call if your form used method='get': verify_captcha($_GET['g-recaptcha-response'], "Secret key here");
** Example call if your form used method='post': verify_captcha($_POST['g-recaptcha-response'], "Secret key here");
*
* We use this at www.nissim.io Enjoy!
*/
function verify_google_captcha($gcaptcha_response, $secret) {
//open a new curl connection
$ch = curl_init();
$url = "https://www.google.com/recaptcha/api/siteverify";
$fields = array(
"secret" => $secret,
"response" => $gcaptcha_response,
);
$fields_string = "";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post request
$result = curl_exec($ch);
//close connection
curl_close($ch);
$json_data = json_decode($result);
//If the captcha was declined, redirect the user to the same page with the query var "captcha" set to "not-entered"
if($json_data->success == false) {
return false;
}
else {
return true;
}
}
$verified = verify_captcha($_POST['g-recaptcha-response'], "_Secret_key_");
if($verified) {
echo "Recaptcha success";
//Do something like write form data to db etc...
}
else{
echo "There was an error with the recaptcha";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment