fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← HTML

HTML / 4 MIN READ

Recaptcha

Securing forms with Recaptcha

From the original Fervor library. Examples may use older package versions.

Alright, let’s get into the magical world of adding reCAPTCHA to your website, vanilla style! Imagine reCAPTCHA as your website’s bouncer, keeping the riff-raff (spam and bots) out of your exclusive online party.

Step 1: Sign up for reCAPTCHA

First up, you need to get yourself a key to the reCAPTCHA kingdom. This means heading over to Google’s reCAPTCHA website. Here’s how:

  • Visit the Google reCAPTCHA site.
  • Sign in with your Google account if you haven’t already.
  • Choose the type of reCAPTCHA you want to use. For a vanilla website, I’d recommend starting with reCAPTCHA v2 for its simplicity and effectiveness. You’ll see options like “I’m not a robot” Checkbox or Invisible reCAPTCHA.
  • Register your website by entering its domain, selecting the reCAPTCHA type, and agreeing to the terms.
  • Boom! You’ll get a site key and a secret key. Think of these as the “Open Sesame” to your website’s new gate.

Step 2: Plant the reCAPTCHA widget in your HTML

Now, let’s embed the reCAPTCHA widget into your website. It’s like planting a magical shield on your webpage.

  • Open your website’s HTML file where you want the reCAPTCHA.
  • Insert this snippet where you’d like the reCAPTCHA to appear:
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY_HERE"></div>

Replace YOUR_SITE_KEY_HERE with your actual site key.

  • Add the reCAPTCHA script tag right before the closing </body> tag in your HTML:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Step 3: Verify the reCAPTCHA response on your server

Imagine catching a fish. The reCAPTCHA widget is the net, and now you need to make sure you’ve caught something legitimate.

  • When the user submits the form on your site, a g-recaptcha-response parameter will be sent. You’ll need to verify this response with Google to ensure the user passed the reCAPTCHA test.
  • In your server-side code (this could be PHP, Python, Node.js, etc.), send a POST request to Google with the response token, your secret key, and the user’s IP address (optional). Here’s a basic example in PHP:
$secretKey = 'YOUR_SECRET_KEY';
$response = $_POST['g-recaptcha-response'];
$verify = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$response}");
$verified = json_decode($verify);
if ($verified->success) {
    // Success! Your user is not a robot (probably).
} else {
    // Handle the failure as a bot or failed verification.
}

Replace YOUR_SECRET_KEY with your actual secret key.

Step 4: Test Your Fortress

Finally, don the armor of a knight and test your fortress’s defenses. Try submitting your form with and without completing the reCAPTCHA to ensure it behaves as expected.

And there you have it! Your website is now fortified with reCAPTCHA, keeping those pesky bots at bay while letting your human guests through. If you run into any dragons along the way (a.k.a. issues or errors), feel free to ask for help. Happy coding, noble web wizard!

Bonus— Super Complete step by step

Alright, let’s dive into a simple tutorial on implementing reCAPTCHA v3 on your website using vanilla HTML and PHP. This tutorial aims to protect your site from spam and abuse without interrupting user experience.

Step 1: Register for reCAPTCHA v3 Keys

  • Go to the reCAPTCHA Admin console and register your site.
  • Select reCAPTCHA v3, name your site, and note your site key and secret key.

Step 2: Frontend Implementation

Automatically Bind the Challenge to a Button

  1. Load the JavaScript API in your HTML:
<script src="https://www.google.com/recaptcha/api.js"></script>
  1. Add a callback function to handle the token:
<script>
function onSubmit(token) {
  document.getElementById("demo-form").submit();
}
</script>
  1. Modify your submit button with data attributes for reCAPTCHA:
<button class="g-recaptcha" 
        data-sitekey="YOUR_SITE_KEY" 
        data-callback='onSubmit' 
        data-action='submit'>Submit</button>

Replace YOUR_SITE_KEY with your actual site key.

Programmatically Invoke the Challenge

If you need more control over when reCAPTCHA runs:

  1. Load the JavaScript API with your site key:
<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY"></script>
  1. Invoke reCAPTCHA on specific user actions:
<script>
function onClick(e) {
  e.preventDefault();
  grecaptcha.ready(function() {
    grecaptcha.execute('YOUR_SITE_KEY', {action: 'submit'}).then(function(token) {
        // Logic to submit token to your backend here.
    });
  });
}
</script>

Step 3: Backend Verification with PHP

  1. Capture the reCAPTCHA token sent with your form data.
  2. Send a POST request to Google’s verification URL including the token and your secret key:
$secretKey = 'YOUR_SECRET_KEY';
$response = $_POST['g-recaptcha-response'];
$verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$response}");
$responseData = json_decode($verifyResponse);
if ($responseData->success && $responseData->score >= 0.5) {
    // Handle pass
} else {
    // Handle fail
}

Step 4: Interpret the Score

  • Use the score (0.0 to 1.0) to decide how to handle the request. A score closer to 1.0 indicates a good interaction.

By integrating reCAPTCHA v3, you can analyze traffic without affecting user experience, adjusting sensitivity and taking action based on user scores. Visit the official documentation for more detailed instructions and best practices.

Keep your curiosity going.Explore more HTML →
287 TUTORIALS · 22 TOPICSREADY