Skip to content

Instantly share code, notes, and snippets.

@jazeabby
Last active July 2, 2019 10:22
Show Gist options
  • Save jazeabby/0c5f907943f22d24fe48c0964e4831af to your computer and use it in GitHub Desktop.
Save jazeabby/0c5f907943f22d24fe48c0964e4831af to your computer and use it in GitHub Desktop.
This helper can be used as a reference to implement Google Recaptcha v3 alognwith grecaptcha.js
<?php
/**
* @author Abhishek Jain
* @email jazeabby@gmail.com
* @create date 2019-07-02 12:08:44
* @modify date 2019-07-02 12:08:44
* @desc Helper to Implement Google Recaptcha V3
* Update:
0. Pleace your Google-server-secret and google-client-key before proceeding
Create these keys at: https://www.google.com/u/1/recaptcha/admin/create
1. Call grec_init('form_id') without # to include the script and input value wherever it is called.
2. Call grec_verify() to check if the submitted token is verified by Google or not.
*/
/**
* Loads the google Recaptcha v3 Library and the default function to return token from
* @param string form_id on which the captcha is to be included
*/
function grec_init($form_id = NULL)
{
if($form_id != NULL){
grec_create($form_id);
}
// initialise the google recaptcha code
// Google site key
$key = '{your-google-captcha-client-key}';
echo '<script src="https://www.google.com/recaptcha/api.js?render='.$key.'"></script>';
?>
<script type="text/javascript">
grecaptcha.ready(function() {
grecaptcha.execute('<?php echo $key;?>', {action: '<?php echo $form_id ?? "default";?>'}).then(function(token) {
$("#GrecaptchaResponse").val(token);
return true;
});
});
</script>
<?php
}
/**
* This function if called will just include input in the form available.
*/
function grec_create($form_id = "")
{
echo '<input type="hidden" name="g-recaptcha-response" id="GrecaptchaResponse" value="" form="'.$form_id.'">';
}
/**
* The function checks the post value and returns true/false as per the post input
*/
function grec_verify()
{
if(!isset($_POST['g-recaptcha-response'])){
return false;
}
$token = $_POST['g-recaptcha-response'];
// google server site secret
$secretKey = '{your-google-captcha-server-secret}';
$data = array('secret' => $secretKey, 'response' => $token);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.google.com/recaptcha/api/siteverify",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
log_message('error',"cURL Error #:" . $err);
}
$response = json_decode($response);
if(isset($response->success) ) {
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment