Skip to content

FORM WITH ReCaptv3 Demo

Deyvin Josep Tinoco edited this page Jul 16, 2025 · 1 revision

HTML Form (index.html) First, let's create the HTML for your form. This includes the Bootstrap 5 styling and the necessary JavaScript for reCAPTCHA v3. Remember to replace YOUR_RECAPTCHA_SITE_KEY with your actual reCAPTCHA site key.

HTML

`

<title>Formulario de Contacto</title> <script src="https://www.google.com/recaptcha/api.js?render=YOUR_RECAPTCHA_SITE_KEY"></script> <style> body { background-color: #f8f9fa; } .container { max-width: 600px; margin-top: 50px; padding: 30px; background-color: #fff; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } </style>

Contáctanos

Nombre completo
Correo electrónico
Número de teléfono
Mensaje <textarea class="form-control" id="message" name="message" rows="5" required></textarea>
Enviar Mensaje
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>

<script>
    document.getElementById('contactForm').addEventListener('submit', function(event) {
        event.preventDefault(); // Prevent default form submission

        grecaptcha.ready(function() {
            grecaptcha.execute('YOUR_RECAPTCHA_SITE_KEY', {action: 'submit_form'}).then(function(token) {
                document.getElementById('recaptchaResponse').value = token;
                // Now submit the form manually after reCAPTCHA token is obtained
                event.target.submit();
            });
        });
    });
</script>
`

Key things to customize in index.html:

YOUR_RECAPTCHA_SITE_KEY: You'll get this when you register your site with Google reCAPTCHA. Make sure to replace both instances of this placeholder.

The grecaptcha.execute call is crucial. It runs reCAPTCHA in the background and gets a token, which is then placed into a hidden input field named recaptchaResponse. This token is what your PHP script will verify.

PHP Processing (process_form.php) Next, create a PHP file named process_form.php. This script will receive the form data, verify the reCAPTCHA token with Google, and then you can add your logic to handle the form submission (e.g., send an email, save to a database). Remember to replace YOUR_RECAPTCHA_SECRET_KEY with your actual reCAPTCHA secret key.

PHP

`<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $fullName = htmlspecialchars(trim($_POST['fullName'])); $email = htmlspecialchars(trim($_POST['email'])); $phone = htmlspecialchars(trim($_POST['phone'])); $message = htmlspecialchars(trim($_POST['message'])); $recaptchaResponse = $_POST['recaptchaResponse'];

// Your reCAPTCHA secret key
$secretKey = 'YOUR_RECAPTCHA_SECRET_KEY';

// Verify reCAPTCHA token
$verifyUrl = "https://www.google.com/recaptcha/api/siteverify";
$response = file_get_contents($verifyUrl . "?secret=" . $secretKey . "&response=" . $recaptchaResponse);
$responseData = json_decode($response);

if ($responseData->success && $responseData->score >= 0.5) {
    // reCAPTCHA verification successful (score 0.5 is a common threshold, adjust as needed)
    // You can also check $responseData->action if you set it in the JS

    // --- Start of your form processing logic ---

    $to = "your_email@example.com"; // Replace with the email address where you want to receive messages
    $subject = "Nuevo mensaje desde el formulario de contacto";
    $headers = "From: " . $email . "\r\n";
    $headers .= "Reply-To: " . $email . "\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";

    $email_body = "
    <html>
    <head>
        <title>Nuevo Mensaje de Contacto</title>
    </head>
    <body>
        <p><strong>Nombre Completo:</strong> {$fullName}</p>
        <p><strong>Correo Electrónico:</strong> {$email}</p>
        <p><strong>Número de Teléfono:</strong> " . ($phone ? $phone : 'No proporcionado') . "</p>
        <p><strong>Mensaje:</strong></p>
        <p>{$message}</p>
    </body>
    </html>
    ";

    if (mail($to, $subject, $email_body, $headers)) {
        echo "¡Gracias por tu mensaje! Nos pondremos en contacto contigo pronto.";
        // Optionally, redirect to a success page: header('Location: success.html');
    } else {
        echo "Lo sentimos, hubo un error al enviar tu mensaje. Por favor, inténtalo de nuevo más tarde.";
    }

    // --- End of your form processing logic ---

} else {
    // reCAPTCHA verification failed or score too low
    // This could indicate a bot or suspicious activity
    echo "Error de verificación de reCAPTCHA. Por favor, inténtalo de nuevo.";
    // You might want to log this for security analysis
    // error_log("reCAPTCHA failed for IP: " . $_SERVER['REMOTE_ADDR'] . " Score: " . $responseData->score);
}

} else { // If someone tries to access process_form.php directly echo "Acceso no autorizado."; } ?>`

Key things to customize in process_form.php:

YOUR_RECAPTCHA_SECRET_KEY: This is your server-side reCAPTCHA key. Keep this secure and never expose it in your front-end code.

$to = "your_email@example.com";: Change this to the email address where you want to receive the form submissions.

$responseData->score >= 0.5: This is the reCAPTCHA score threshold. Scores closer to 1 are likely good interactions, while scores closer to 0 are likely bots. You might need to adjust this value based on your traffic and desired strictness.

The mail() function is used here for sending emails. For more robust email sending (e.g., with authentication, HTML emails with attachments, etc.), consider using a dedicated PHP mailer library like PHPMailer or Symfony Mailer.

Before You Deploy Get your reCAPTCHA Keys: Go to the Google reCAPTCHA Admin Console and register your website. Choose reCAPTCHA v3. You will be given a Site Key (for your HTML) and a Secret Key (for your PHP).

Replace Placeholders: Carefully replace YOUR_RECAPTCHA_SITE_KEY in index.html and YOUR_RECAPTCHA_SECRET_KEY in process_form.php with your actual keys.

Upload Files: Place both index.html and process_form.php on your web server.

Test Thoroughly: Fill out the form and submit it to ensure everything is working as expected. Check your target email inbox.

This setup provides a solid foundation for your form with reCAPTCHA v3. Let me know if you have any other questions or need further modifications!

Clone this wiki locally