A simple example of a contact form verified by Google reCAPTCHA v3 with pure JavaScript and PHP
tldr; skip to code at the bottom.
Relevant reCAPTCHA docs etc:
- Create keys: https://www.google.com/recaptcha/admin/create
- Frontend integration: https://developers.google.com/recaptcha/docs/v3
- Backend verification: https://developers.google.com/recaptcha/docs/verify
(If Google are listening, we love your work and it would be wonderful to have some more elaborate examples linked to the above pages please.)
Overview:
- Get keys from Google
- Load recaptcha/api.js in head of html
- Hijack form submission with JavaScript and at that point get token from Google
- Submit form with token to your server
- Make request from your website’s backend to Google to verify the
form submission - Interpret the response and proceed as necessary
Important to note: the ‘success’ response parameter indicates only whether or not the captcha was evaluated successfully, it doesn’t indicate whether the submission was likely to be spam or not.
The ‘score’ parameter is the result you need to know about. The higher the score (a number between 0 and 1) the more likely a submission is genuine, and it’s upto you what threshold (e.g. 0.5) to accept.
In detail:
Add the following line to the head of your HTML to load the recaptcha api.js code:
<script src="https://www.google.com/recaptcha/api.js?render=$reCAPTCHA_site_key"></script>
(where $reCAPTCHA_site_key
is your public ‘site key’, which I’ve saved in a ‘config.php’ file.)
You need to submit a token (received from Google & unique to each form submission) to your server. I think it’s simplest to send it via POST along with the rest of the form data. To that end I include a hidden field in the form as follows:
<form id="contactForm" method="post" action="contact">
<!-- other form inputs -->
<input type="hidden" id="gRecaptchaResponse" name="gRecaptchaResponse">
<input type="submit" name="contact_submit" value="Send message">
</form>
(Nb. “contact” is contact.php, but I’ve ‘rewritten’ the url with .htaccess)
Now we need to hijack the default form submission to generate the token. We could generate the token on page load but since the token is only valid for two minutes (if I’m reading the https://developers.google.com/recaptcha/docs/verify page correctly) I think it’s better to fetch it at the point of needing to send it to your site’s server.
To this end I added the following right after the closing form tag:
<script>
contactForm.addEventListener('submit', event => {
event.preventDefault()
validate(contactForm)
});
</script>
I’ve put the validate(form)
function just before the closing body tag:
function validate(form) {
//perform optional error checking on form. If no errors then request a token and put it into the hidden field
getRecaptchaToken(form)
}
//some other (optional) form validation functions
function getRecaptchaToken(form) {
grecaptcha.ready(function() {
grecaptcha.execute($reCAPTCHA_site_key, {action: 'contactForm'}).then(function(token) {
gRecaptchaResponse.value = token //set the value of the hidden field
form.submit() //submit the form
});
});
}
Notes:
$reCAPTCHA_site_key
is your public Site Keyaction: 'contactForm'
identifies the submission of this particular
form in the Google reCAPTCHA dashboard, and confirming it is as expected in the backend is a recommended extra
security step
In the main PHP file, when the form submission is received:
//get the IP address of the origin of the submission
$ip = $_SERVER['REMOTE_ADDR'];
//construct the url to send your private Secret Key, token and (optionally) IP address of the form submitter to Google to get a spam rating for the submission (I've saved '$reCAPTCHA_secret_key' in config.php)
$url="https://www.google.com/recaptcha/api/siteverify?secret=" . urlencode($reCAPTCHA_secret_key) . '&response=" . urlencode($g_recaptcha_response) . "&remoteip=' . urlencode($ip);
//save the response, e.g. print_r($response) prints { "success": true, "challenge_ts": "2019-07-24T11:19:07Z", "hostname": "your-website-domain.co.uk", "score": 0.9, "action": "contactForm" }
$response = file_get_contents($url);
//decode the response, e.g. print_r($responseKeys) prints Array ( [success] => 1 [challenge_ts] => 2019-07-24T11:19:07Z [hostname] => your-website-domain.co.uk [score] => 0.9 [action] => contactForm )
$responseKeys = json_decode($response, true);
//check if the test was done OK, if the action name is correct and if the score is above your chosen threshold (again, I've saved '$g_recaptcha_allowable_score' in config.php)
if ($responseKeys["success"] && $responseKeys["action"] == 'contactForm') {
if ($responseKeys["score"] >= $g_recaptcha_allowable_score) {
//send email with contact form submission data to site owner/ submit to database/ etc
//redirect to confirmation page or whatever you need to do
} elseif ($responseKeys["score"] < $g_recaptcha_allowable_score) {
//failed spam test. Offer the visitor the option to try again or use an alternative method of contact.
}
} elseif($responseKeys["error-codes"]) { //optional
//handle errors. See notes below for possible error codes
//personally I'm probably going to handle errors in much the same way by sending myself a the error code for debugging and offering the visitor the option to try again or use an alternative method of contact
} else {
//unkown screw up. Again, offer the visitor the option to try again or use an alternative method of contact.
}
Notes:
- This is is the data which will be in the response from Google
(returned as a JSON object):
{
"success": true|false, // whether this request was a valid reCAPTCHA token for your site
"score": number // the score for this request (0.0 - 1.0)
"action": string // the action name for this request (important to verify)
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
- These are the possible error codes:
- missing-input-secret: The secret parameter is missing.
- invalid-input-secret: The secret parameter is invalid or malformed.
- missing-input-response: The response parameter is missing.
- invalid-input-response: The response parameter is invalid or malformed.
- bad-request: The request is invalid or malformed.
- timeout-or-duplicate: The response is no longer valid; either is too
old or has been used previously.
Putting it all together:
contact.php
<?php //contact.php
require_once('config.php');
//do server-side validation of other form fields
if (/*form has been submitted and has passed server-side validation of the other form fields*/) {
$ip = $_SERVER['REMOTE_ADDR'];
$url="https://www.google.com/recaptcha/api/siteverify?secret=" . urlencode($reCAPTCHA_secret_key) . '&response=" . urlencode($g_recaptcha_response) . "&remoteip=' . urlencode($ip);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
if ($responseKeys["success"] && $responseKeys["action"] == 'contactForm') {
if ($responseKeys["score"] >= $g_recaptcha_allowable_score) {
//send email with contact form submission data to site owner/ submit to database/ etc
//redirect to confirmation page or whatever you need to do
} elseif ($responseKeys["score"] < $g_recaptcha_allowable_score) {
//failed spam test. Offer the visitor the option to try again or use an alternative method of contact.
}
} elseif($responseKeys["error-codes"]) { //optional
//handle errors. See notes below for possible error codes
//(I handle errors by sending myself an email with the error code for debugging and offering the visitor the option to try again or use an alternative method of contact)
} else {
//unkown screw up. Again, offer the visitor the option to try again or use an alternative method of contact.
}
exit;
} else { //(re)display the page with the form
echo <<<_END
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact | Your website</title>
<link rel="stylesheet" href="https://stackoverflow.com/questions/50405977/css/style.css">
<script src="https://www.google.com/recaptcha/api.js?render=$reCAPTCHA_site_key"></script>
</head>
<body>
<!-- header etc -->
<form id="contactForm" method="post" action="contact">
//other form inputs
<input type="hidden" id="gRecaptchaResponse" name="gRecaptchaResponse">
<input type="submit" name="contact_submit" value="Send message">
</form>
<script>
contactForm.addEventListener('submit', event => {
event.preventDefault()
validate(contactForm)
});
</script>
<!-- footer etc -->
<script>
function validate(form) {
//perform optional client-side error checking of the form. If no errors are found then request a token and put it into the hidden field. Finally submit the form.
getRecaptchaToken(form)
}
//some (optional) form field validation functions
function getRecaptchaToken(form) {
grecaptcha.ready(function() {
grecaptcha.execute($reCAPTCHA_site_key, {action: 'contactForm'}).then(function(token) {
gRecaptchaResponse.value = token
form.submit()
});
});
}
</script>
</body>
</html>
_END;
config.php
<?php //config.php
//other site settings
// Google reCAPTCHA v3 keys
// For reducing spam contact form submissions
// Site key (public)
$reCAPTCHA_site_key = 'N0t-a-real-0N3_JHbnbUJ-BLAHBLAH_Blahblah';
// Secret key
$reCAPTCHA_secret_key = 'N0t-a-real-0N3_i77tyYGH7Ty6UfG-blah';
// Min score returned from reCAPTCHA to allow form submission
$g_recaptcha_allowable_score = 0.5; //Number between 0 and 1. You choose this. Setting a number closer to 0 will let through more spam, closer to 1 and you may start to block valid submissions.