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 the 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 via AJAX (the page will not reload) and process the form values with PHP. At last, 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 in case 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.

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 form's submission. We will do this by calling the grecaptcha.reset(); function.

Template Categories

Users

179,314

Downloads

441,672

About Bootstrapious

You will find here a great collection of exclusive Bootstrap templates and themes ready to be used in your next project. All templates are fully responsive, HTML valid, premium quality and last but not least - a majority of them is free to use!

Navigate

About Bootstrap framework

Bootstrap is the most popular HTML and CSS framework for developing responsive websites. Bootstrap makes front-end web development faster and easier. It's made for folks of all skill levels, devices of all shapes, and projects of all sizes.