Skip to content

Instantly share code, notes, and snippets.

@andreipa
Created May 10, 2020 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreipa/52911bed90d6c989d88e086e47d92a82 to your computer and use it in GitHub Desktop.
Save andreipa/52911bed90d6c989d88e086e47d92a82 to your computer and use it in GitHub Desktop.
Validate Google reCaptcha with PHP.
/**
* Validate Google reCAPTCHA
*
* @link https://developers.google.com/recaptcha/docs/v3
* @author Andrei Andrade
*
* @param mixed $publicKey The shared key between your site and reCAPTCHA.
* @param mixed $privateKey The user response token provided by the reCAPTCHA client-side integration on your site.
* @param float $score Score value (1.0 is very likely a good interaction, 0.0 is very likely a bot).
* @param null|mixed $remoteIp Optional. The user's IP address.
*
* @return bool
*/
function isGoogleReCaptchaValid($publicKey, $privateKey, $score = 0.5, $remoteIp = null)
{
$post = [
'secret' => $privateKey,
'response' => $publicKey,
'remoteip' => $remoteIp,
];
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
$response = json_decode($response);
curl_close($ch);
if ($response->success && $response->score >= $score) {
return true;
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment