Using reCAPTCHA v3 with Formr
Formr has support for reCAPTCHA v3, and it's super easy to install.
Step 1: Get Your Keys
The first step is to register your site and get your keys, which you can do here: https://google.com/recaptcha/admin/create
Warning
Make sure you select the reCAPTCHA v3 checkbox!
Step 2: Add Your Keys to Formr
Next we want to tell Formr that we're using reCAPTCHA, and we do that by using the recaptcha_secret_key
and recaptcha_site_key
properties.
$form->recaptcha_secret_key = 'REPLACE-WITH-YOUR-SECRET-KEY';
$form->recaptcha_site_key = 'REPLACE-WITH-YOUR-SITE-KEY';
Step 3: Add HTML & JavaScript
We need to add some code to our web page so that Google can generate a score and verify that a human is actually using our form. We do this with the recaptcha_head
and recaptcha_body
methods. These methods will print the appropriate HTML and JavaScript to make sure our reCAPTCHA works.
$form->recaptcha_head();
$form->recaptcha_body();
Step 4: Pass or Fail?
All that's left is to verify if the reCAPTCHA passed after the form was submitted, and we do that with the recaptcha_passed
method.
if($form->recaptcha_passed()) {
// reCAPTCHA passed
}
if(! $form->recaptcha_passed()) {
// reCAPTCHA failed
}
Full Example
<?php
$form = new Formr\Formr();
$form->recaptcha_site_key = 'REPLACE-WITH-YOUR-SITE-KEY';
$form->recaptcha_secret_key = 'REPLACE-WITH-YOUR-SECRET-KEY';
if($form->submitted()) {
if($form->recaptcha_passed()) {
$form->success_message('reCAPTCHA Passed!')
}
}
?>
<html>
<head>
<title>Formr</title>
<?php
# includes a reCAPTCHA JavaScript file from Google
$form->recaptcha_head();
?>
</head>
<body>
<?php
$form->messages();
# build our form
$form->create_form('Name, Email, Comments|textarea');
# print the reCAPTCHA JavaScript
$form->recaptcha_body();
?>
</body>
</html>