Skip to content

Instantly share code, notes, and snippets.

@developer-anuragsingh
Last active January 20, 2023 11:13
Show Gist options
  • Save developer-anuragsingh/abba5cc9a0e5ee13ff54859dd243916e to your computer and use it in GitHub Desktop.
Save developer-anuragsingh/abba5cc9a0e5ee13ff54859dd243916e to your computer and use it in GitHub Desktop.
Add Google reCaptcha 3 (invisible) on frontend & backend in PHP | HTML | jQuery
<?php
// Define Google Recaptcha Keys here
// Reference - https://www.google.com/recaptcha/admin#list
return [
'v2-standard' => [
'site' => '6LXXXXXXXXXXXXXXXXXXXXXXXX',
'secret' => '6LXXXXXXXXXXXXXXXXXXXXXXXX',
],
'v2-invisible' => [
'site' => '6LXXXXXXXXXXXXXXXXXXXXXXXX',
'secret' => '6LXXXXXXXXXXXXXXXXXXXXXXXX',
],
'v3' => [
'site' => '6LXXXXXXXXXXXXXXXXXXXXXXXX',
'secret' => '6LXXXXXXXXXXXXXXXXXXXXXXXX',
],
];
<?php
// Check if form was submitted:
$site_key = '';
$secret = '';
// Copy the config.php.dist file to config.php and update it with your keys to run the examples
if ( $site_key == '' && is_readable( __DIR__ . '/config.php' ) ) {
$config = include __DIR__ . '/config.php';
$site_key = $config['v3']['site'];
$secret = $config['v3']['secret'];
}
if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) {
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = $secret;
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request:
$recaptcha_response = file_get_contents( $recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response );
$google_recaptcha_response = json_decode( $recaptcha_response );
if ( ! $google_recaptcha_response->success || empty( $google_recaptcha_response->success ) ) {
$response = array(
'status' => false,
'msg' => 'reCAPTCHA verification failed.',
);
} else {
if ( $google_recaptcha_response->score >= 0.5 ) { // Verified
// Process form here
$response = array(
'status' => true,
'msg' => 'reCAPTCHA verification successful.',
'data' => $google_recaptcha_response,
);
} else { // Not verified - show form error
$response = array(
'status' => false,
'msg' => 'reCAPTCHA verification failed. Response score is less then 0.5',
'data' => $google_recaptcha_response,
);
}
}
echo json_encode( $response );
die;
// return json_encode( $response );
}
- Add Google reCaptcha 3 on HTML form
- On form load, get the google recaptcha response in hidden form field
- On form submit, Send recaptha field value to php file
- Validate google captcha with server side
<?php
$site_key = '';
$secret = '';
// Copy the config.php.dist file to config.php and update it with your keys to run the examples
if ( $site_key == '' && is_readable( __DIR__ . '/config.php' ) ) {
$config = include __DIR__ . '/config.php';
$site_key = $config['v3']['site'];
$secret = $config['v3']['secret'];
}
$lang = 'en';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Google Recaptcha 3</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.0/dist/jquery.validate.min.js"></script>
<script src="../DIRECTORY_PATH/validation.js"></script>
<script src="https://www.google.com/recaptcha/api.js?render=<?php echo $site_key; ?>"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('<?php echo $site_key; ?>', { action: 'contact' }).then(function (token) {
recaptchaResponse.value = token;
});
});
</script>
</head>
<body>
<?php
if ( $site_key === '' || $secret === '' ) :
?>
<h2>Add your keys</h2>
<p>If you do not have keys already then visit <kbd> <a href="https://www.google.com/recaptcha/admin">https://www.google.com/recaptcha/admin</a></kbd>
to generate them. Edit this file and set the respective keys in <kbd>$site_key</kbd> and <kbd>$secret</kbd>. Reload
the page after this.</p>
<?php
else :
?>
<h1 class="display-1 text-center">Google Recaptcha 3</h1>
<hr>
<hr>
<br>
<div class="container">
<div class="row justify-content-center">
<div class="col-6">
<form method="POST" id="registerForm">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="text" class="form-control" id="user_email" name="user_email" aria-describedby="emailHelp" placeholder="Enter email" required>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone
else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="user_password" name="user_password" placeholder="Password">
</div>
<div class="form-group form-check">
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</div>
<input class="submit" type="submit" value="Submit" class="btn btn-primary">
</form>
</div>
</div>
</div>
<?php endif; ?>
</body>
</html>
jQuery(document).ready(function ($) {
$("#registerForm").validate({
rules: {
user_email: {
required: true
},
recaptcha_response: {
required: true,
minlength: 8,
}
},
messages: {
user_email: {
required: "We need your email address to contact you",
},
recaptcha_response: {
required: "recaptcha Response is reqiuiered"
}
},
submitHandler: function (form) {
dataPayload = {
user_email: $('#user_email').val(),
recaptcha_response: $('#recaptchaResponse').val(),
};
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/..DIRECTORY_PATH../form-process.php",
data: dataPayload,
success: function (result) {
str = JSON.stringify(result);
str = JSON.stringify(result, null, 4);
console.log("result =>" + str);
// Handle the response here
},
error: function (jqXHR, textStatus, errorThrown) {
str = JSON.stringify(jqXHR);
str = JSON.stringify(jqXHR, null, 4);
console.log("jqXHR =>" + str);
console.log("textStatus =>" + textStatus);
console.log("errorThrown => " + errorThrown);
}
});
}
});
});
@hikmalwebid
Copy link

awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment