Use code captcha in two forms

Learn use code captcha in two forms with practical examples, diagrams, and best practices. Covers forms, recaptcha, code-reuse development techniques with visual explanations.

Implementing ReCAPTCHA Across Multiple Forms

Illustration of a shield protecting multiple web forms, symbolizing reCAPTCHA security

Learn how to effectively integrate and reuse Google reCAPTCHA v2 (checkbox) across different forms on your website, ensuring robust spam protection without redundant code.

Integrating reCAPTCHA into your web forms is crucial for preventing spam and bot submissions. While Google reCAPTCHA v2 (checkbox) is straightforward to implement on a single form, applying it to multiple forms on the same page or across different pages requires a thoughtful approach to avoid conflicts and ensure proper functionality. This article will guide you through setting up reCAPTCHA once and reusing its functionality for various forms, enhancing your site's security and user experience.

Understanding reCAPTCHA v2 (Checkbox) Basics

Google reCAPTCHA v2 (checkbox) works by presenting users with a simple 'I'm not a robot' checkbox. Upon submission, a token is generated and sent to your server for verification. The key to reusing reCAPTCHA lies in understanding how to render it dynamically and associate the generated token with the correct form submission.

flowchart TD
    A[User loads page with forms] --> B{reCAPTCHA Script Loaded}
    B --> C[reCAPTCHA Rendered on Form 1]
    C --> D[User interacts with Form 1]
    D --> E{reCAPTCHA Token Generated}
    E --> F[Form 1 Submitted with Token]
    F --> G[Server Verifies Token]
    G --> H{Verification Result}
    H -- Valid --> I[Process Form 1 Data]
    H -- Invalid --> J[Reject Form 1 Submission]
    C -- User interacts with Form 2 --> K[reCAPTCHA Rendered on Form 2]
    K --> L{reCAPTCHA Token Generated}
    L --> M[Form 2 Submitted with Token]

Basic reCAPTCHA v2 (Checkbox) Workflow

Initial Setup: Loading the reCAPTCHA API

The first step is to load the reCAPTCHA API script asynchronously. This script provides the grecaptcha object, which is essential for rendering and interacting with reCAPTCHA. Place this script tag in your HTML <head> or just before the closing </body> tag.

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>

Loading the reCAPTCHA API script with an explicit render callback.

Dynamic Rendering for Multiple Forms

To use reCAPTCHA on multiple forms, you'll need to render it explicitly for each form. This involves creating a div element with a specific class or ID where reCAPTCHA will be placed, and then using JavaScript to render it. Each reCAPTCHA instance will generate a unique response token that needs to be included with its respective form submission.

<!-- Form 1 -->
<form id="form1" action="/submit-form1" method="POST">
    <input type="text" name="name" placeholder="Your Name">
    <div class="g-recaptcha" data-recaptcha-id="form1-captcha"></div>
    <input type="hidden" name="g-recaptcha-response" id="form1-recaptcha-response">
    <button type="submit">Submit Form 1</button>
</form>

<!-- Form 2 -->
<form id="form2" action="/submit-form2" method="POST">
    <input type="email" name="email" placeholder="Your Email">
    <div class="g-recaptcha" data-recaptcha-id="form2-captcha"></div>
    <input type="hidden" name="g-recaptcha-response" id="form2-recaptcha-response">
    <button type="submit">Submit Form 2</button>
</form>

HTML structure for two forms, each with a reCAPTCHA placeholder and a hidden input for the token.

var recaptchaWidgets = {};

var onloadCallback = function() {
    // Find all reCAPTCHA placeholders
    var recaptchaDivs = document.querySelectorAll('.g-recaptcha');

    recaptchaDivs.forEach(function(div) {
        var widgetId = grecaptcha.render(div, {
            'sitekey': 'YOUR_SITE_KEY',
            'callback': function(response) {
                // Get the data-recaptcha-id from the div
                var recaptchaId = div.getAttribute('data-recaptcha-id');
                // Find the corresponding hidden input and set its value
                document.getElementById(recaptchaId.replace('-captcha', '-recaptcha-response')).value = response;
            },
            'expired-callback': function() {
                // Handle token expiration for this specific widget
                var recaptchaId = div.getAttribute('data-recaptcha-id');
                document.getElementById(recaptchaId.replace('-captcha', '-recaptcha-response')).value = '';
            }
        });
        // Store widget ID if needed for reset or other operations
        recaptchaWidgets[div.getAttribute('data-recaptcha-id')] = widgetId;
    });
};

// Example of how to reset a specific reCAPTCHA widget after form submission
function resetRecaptcha(formId) {
    var recaptchaId = formId + '-captcha';
    if (recaptchaWidgets[recaptchaId]) {
        grecaptcha.reset(recaptchaWidgets[recaptchaId]);
        document.getElementById(formId + '-recaptcha-response').value = ''; // Clear hidden input
    }
}

JavaScript to explicitly render multiple reCAPTCHA widgets and handle their responses.

Server-Side Verification

Regardless of how many forms you have, the server-side verification process remains the same. When a form is submitted, your server receives the g-recaptcha-response token. You must send this token, along with your secret key, to Google's verification API endpoint. Google will respond with a JSON object indicating whether the verification was successful.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $recaptcha_response = $_POST['g-recaptcha-response'];
    $secret_key = 'YOUR_SECRET_KEY'; // Replace with your actual secret key

    $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
    $data = [
        'secret' => $secret_key,
        'response' => $recaptcha_response
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        ]
    ];
    $context  = stream_context_create($options);
    $result = file_get_contents($verify_url, false, $context);
    $response_data = json_decode($result, true);

    if ($response_data['success']) {
        // reCAPTCHA verification successful
        // Process form data for the specific form that was submitted
        if (isset($_POST['name'])) {
            echo "Form 1 submitted successfully!";
            // Handle Form 1 data
        } elseif (isset($_POST['email'])) {
            echo "Form 2 submitted successfully!";
            // Handle Form 2 data
        }
    } else {
        // reCAPTCHA verification failed
        echo "reCAPTCHA verification failed. Please try again.";
        // Log errors: $response_data['error-codes']
    }
}
?>

Example PHP server-side verification for reCAPTCHA.

1. Get reCAPTCHA Keys

Register your website with Google reCAPTCHA to obtain your Site Key (public) and Secret Key (private).

2. Load API Script

Include the reCAPTCHA API script in your HTML with onload and render=explicit parameters.

3. Prepare HTML Forms

For each form, add a div with class g-recaptcha and a unique data-recaptcha-id, plus a hidden input field for the token.

4. Implement JavaScript Rendering

Write an onloadCallback function to iterate through your reCAPTCHA divs, render each widget, and assign the response token to the correct hidden input.

5. Server-Side Verification

On your server, verify the g-recaptcha-response token against Google's API using your secret key before processing any form data.