Bootstrap ReCaptcha Form Tutorial
Many of you asked for a tutorial on implementing a Captcha to the Bootstrap forms; here it is. I chose a popular Captcha solution, Google's ReCaptcha, for verification.
In the tutorial, I will be using a working HTML contact form from my previous tutorial.
Our form will be using HTML5 sprinkled with some Bootstrap scaffolding and a JavaScript validator. We will submit it with AJAX (the page will not reload) and process the form values with PHP.
Finally, we will send an email with PHP and return a response to the original page that will be shown in a status message above the form.
I will mostly focus on working with Captcha today, so if you have missed my last tutorial, have at least a quick look at it.
Explore the demo or download the files we will be working with. And we can start right now.
Note: I updated this tutorial to Bootstrap 4 already but no worries if you are still using Bootstrap 3 in your project. Bootstrap 3 version is also part of the download.
Demo and links
Demo Download files Demo Bootstrap 3
Register your site
To use ReCaptcha, you will need to register your website on ReCaptcha's website first.
After successful registration, you will get a pair of keys to use with your ReCaptcha. Leave the page open or copy the keys to a text file; we will need them soon.
HTML
We will use the contact form's template from the previous tutorial, + we will add a reCAPTCHA element and a hidden input next to it to help us with the JavaScript validation.
Pay attention to these changes:
- Replace the
data-
sitekey
attribute with your Site key. ReCaptcha will appear in this div -<div class="g-recaptcha" data-sitekey="6LfKURIUAAAAAO50vlwWZkyK_G2ywqE52NU7YO0S"></div>
- Include the ReCaptcha JS to initialize ReCaptcha on the page -
<script src='https://www.google.com/recaptcha/api.js'></script>
<html>
<head>
<title>Contact Form Tutorial by Bootstrapious.com</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Lato:300,400,500' rel='stylesheet' type='text/css'>
<link href='custom.css' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-8 offset-xl-2">
<h1>Contact form Tutorial from
<a href="https://bootstrapious.com">Bootstrapious.com</a>
</h1>
<p class="lead">This is a demo for our tutorial dedicated to crafting working Bootstrap contact form with PHP and AJAX background.
At this part, we will add Google's ReCaptcha too.</p>
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LfKURIUAAAAAO50vlwWZkyK_G2ywqE52NU7YO0S" data-callback="verifyRecaptchaCallback" data-expired-callback="expiredRecaptchaCallback"></div>
<input class="form-control d-none" data-recaptcha="true" required data-error="Please complete the Captcha">
<div class="help-block with-errors"></div>
</div>
<input type="submit" class="btn btn-success btn-send" value="Send message">
<p class="text-muted">
<strong>*</strong> These fields are required. Contact form template by
<a href="https://bootstrapious.com/p/bootstrap-recaptcha" target="_blank">Bootstrapious</a>.
</p>
</div>
</form>
</div>
<!-- /.8 -->
</div>
<!-- /.row-->
</div>
<!-- /.container-->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src="validator.js"></script>
<script src="contact.js"></script>
</body>
</html>
PHP
In PHP, we will be using Google's client library that will take care of the verification.
You can use Composer to install it in your project, download it from GitHub or use the version I included in the download package.
Again, pay attention to these changes:
- require the ReCaptcha PHP library -
require('recaptcha-master/src/autoload.php');
- enter your Secret Key -
$recaptchaSecret = 'YOUR_SECRET_KEY';
- initialize the class with your Secret Key -
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret)
; - send a call to validate the ReCaptcha -
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
- throw an exception if the validation fails -
if (!$response->isSuccess()) {...}
The script then composes the email message, sends it, and returns a JSON response. (The script is submitted by AJAX in default)
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'Demo contact form <demo@domain.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <demo@domain.com>';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
// ReCaptch Secret
$recaptchaSecret = '6LfKURIUAAAAAKEPdFXGUiRsQYtEYUnH1-OB5Mgx';
// let's do the sending
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try {
if (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
JavaScript
There will be a few changes in our JavaScript.
As mentioned before, we will add two callbacks for the ReCAPTCHA and change the value of our hidden input <input class="form-control d-none" data-recaptcha="true">
. If the captcha validates, it will have a non-empty value, and this part of the form will validate.
The second change to my previous tutorial will be resetting the ReCaptcha after the form's submission. We will do this by calling the grecaptcha
.reset();
function.
$(function () {
window.verifyRecaptchaCallback = function (response) {
$('input[data-recaptcha]').val(response).trigger('change')
}
window.expiredRecaptchaCallback = function () {
$('input[data-recaptcha]').val("").trigger('change')
}
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
Result
This is it.
You should have a working contact Bootstrap contact form with ReCaptcha and PHP background now.
I hope you have enjoyed the tutorial.
Check out my other Bootstrap tutorials, my Bootstrap freebies, or useful Bootstrap snippets.
FAQs
How do I add "I am not a robot" in HTML?
The most convenient way is to add Google ReCaptcha. Google ReCaptcha is now available as a free, easy-to-use service that helps you prevent spam and abuse.
What is Google ReCaptcha?
ReCaptcha is a free service from Google that helps you prevent spam and abuse on your website. For example, if you have a contact form on your site, spammers may use it to send junk emails. With ReCaptcha, you can verify that the request is coming from a human, not a computer by asking the individual to solve a simple math problem or check a box next to the distorted text.
Google has released several versions of ReCaptcha over the years:
Classic ReCaptcha - launched in 2008, this version of the code is still widely used today and supported in all major browsers
Invisible ReCaptcha - launched in 2013 as an alternative to classic ReCaptcha for websites that want greater flexibility in how they display the code on their pages. Invisible ReCaptcha also allows users to continue interacting with your site without interruptions while they solve challenges. This version only works with modern browsers (Chrome 39+, IE11+).
What is CAPTCHA?
CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart." This is one of many ways we use to verify that you are human. reCAPTCHA uses images that are easy for humans but difficult for computers to recognize, so bots fail while humans succeed.
Is reCAPTCHA a bot?
reCAPTCHA is not a bot. It uses artificial intelligence and machine learning to distinguish between humans and bots, which means it can identify real people and bots.
What does reCAPTCHA do?
reCAPTCHA helps Google protect its users from spam, abuse, and other malicious activities. reCAPTCHA challenges users to verify that they are human by asking them to complete a simple task that computers often have trouble with, like identifying street signs or separating items based on their shapes. Google uses this technology to improve its products and services.