Secure Your Forms with Google reCAPTCHA v2 in PHP: Step-by-Step Guide

Last updated 2 weeks, 4 days ago | 33 views 75     5

Tags:- PHP CAPTCHA

First page link: Protecting Forms Using a CAPTCHA in PHP: A Complete Guide

Great! Here's a detailed article on how to integrate Google reCAPTCHA v2 in a PHP form:


Secure Your Forms with Google reCAPTCHA v2 in PHP: Step-by-Step Guide

Bots can be a real nuisance—spamming contact forms, creating fake accounts, and launching brute-force attacks. Fortunately, Google reCAPTCHA v2 offers an easy and effective way to block automated submissions while allowing humans to interact smoothly.

This guide will walk you through integrating Google reCAPTCHA v2 ("I'm not a robot") into your PHP forms with full code, step-by-step instructions, and useful tips.


Prerequisites

  • A Google account

  • Basic understanding of PHP and HTML

  • PHP server with internet access


Step 1: Get reCAPTCHA API Keys

  1. Go to https://www.google.com/recaptcha/admin

  2. Register a new site

  3. Choose reCAPTCHA v2 > "I'm not a robot" Checkbox

  4. Add your domain (e.g., localhost for local development)

  5. Accept terms and click "Submit"

  6. You’ll get two keys:

    • Site Key (for frontend)

    • Secret Key (for server-side verification)


Folder Structure

/recaptcha-form/
├── index.php         <-- The HTML form
├── process.php       <-- Handles the form and verifies CAPTCHA

1️⃣ Frontend Form – index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>reCAPTCHA Form</title>
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
  <h2>Contact Form with reCAPTCHA</h2>
  <form action="process.php" method="post">
    <label>Name:</label><br>
    <input type="text" name="name" required><br><br>

    <label>Message:</label><br>
    <textarea name="message" required></textarea><br><br>

    <!-- Google reCAPTCHA widget -->
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY_HERE"></div><br>

    <input type="submit" value="Submit">
  </form>
</body>
</html>

Replace "YOUR_SITE_KEY_HERE" with the actual site key from Google.


2️⃣ Backend Verification – process.php

<?php
// Your secret key
$secretKey = "YOUR_SECRET_KEY_HERE";

// User inputs
$name = trim($_POST['name'] ?? '');
$message = trim($_POST['message'] ?? '');

// reCAPTCHA response token
$recaptchaResponse = $_POST['g-recaptcha-response'] ?? '';

// Verify the CAPTCHA
if (!$recaptchaResponse) {
    die("<p style='color:red;'>Please complete the CAPTCHA.</p>");
}

// Verify with Google
$verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';
$response = file_get_contents($verifyUrl . '?secret=' . urlencode($secretKey) . '&response=' . urlencode($recaptchaResponse));
$responseKeys = json_decode($response, true);

// Check result
if ($responseKeys['success']) {
    echo "<h3 style='color:green;'>Form submitted successfully!</h3>";
    echo "<p><strong>Name:</strong> " . htmlspecialchars($name) . "</p>";
    echo "<p><strong>Message:</strong> " . nl2br(htmlspecialchars($message)) . "</p>";
} else {
    echo "<p style='color:red;'>CAPTCHA verification failed. Please try again.</p>";
}
?>

Replace "YOUR_SECRET_KEY_HERE" with the actual secret key from Google.


✅ What Happens Behind the Scenes?

  1. User completes the CAPTCHA challenge.

  2. On form submission, the token (g-recaptcha-response) is sent to your PHP server.

  3. Your server sends a POST request to Google’s API to verify the token.

  4. If valid, the form is processed; if not, an error message is shown.


Tips

  • Always validate other inputs server-side too (don’t rely only on CAPTCHA).

  • Avoid hardcoding keys in production—store them in a config file or environment variable.

  • Use HTTPS to prevent token interception.


⚠️ Common Pitfalls

Problem Solution
CAPTCHA doesn't appear Make sure you’re using the correct site key
Verification fails every time Ensure you're sending the correct secret key and token
reCAPTCHA not submitting Check that the g-recaptcha-response is present and being posted
Localhost issues Register localhost as an allowed domain in reCAPTCHA settings

Conclusion

Google reCAPTCHA v2 is a highly effective, easy-to-implement tool to block bots and automated abuse on your forms. With just a few lines of HTML and PHP, you can protect your forms and improve the integrity of your data.


Would you like an upgrade version using reCAPTCHA v3 (invisible) or AJAX-based form submission with reCAPTCHA

Click here