I stand up for children in need. Please join me in helping this family.

Skip to content
Steven Roland

Creating a Simple PHP Wrapper for Google reCAPTCHA

PHP , HTML

In today's digital landscape, protecting your web forms from spam and abuse is crucial. Google's reCAPTCHA is a popular tool for this purpose, but integrating it into your PHP projects can sometimes be a bit cumbersome. Today, we'll create a simple, reusable PHP wrapper class for Google reCAPTCHA that you can easily incorporate into your projects.

The ReCaptchaWrapper Class

Let's dive into the code for our ReCaptchaWrapper class:

<?php

class ReCaptchaWrapper
{
    private static $siteKey = 'default_site_key';
    private static $secretKey = 'default_secret_key';

    public static function init($siteKey = null, $secretKey = null)
    {
        if ($siteKey !== null) {
            self::$siteKey = $siteKey;
        }

        if ($secretKey !== null) {
            self::$secretKey = $secretKey;
        }
    }

    public static function displayWidget()
    {
        echo '<div class="g-recaptcha" data-sitekey="' . self::$siteKey . '"></div>';
        echo '<script src="https://www.google.com/recaptcha/api.js" async defer></script>';
    }

    public static function verifyResponse($response)
    {
        $url = 'https://www.google.com/recaptcha/api/siteverify';

        $data = [
            'secret' => self::$secretKey,
            'response' => $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($url, false, $context);
        $resultJson = json_decode($result);

        return $resultJson->success;
    }
}

Key Features

  1. Static Methods: The class uses static methods, allowing you to call them without instantiating the class.

  2. Default Keys: It includes default values for the site key and secret key.

  3. Flexible Initialization: The init() method allows you to override the default keys if needed.

  4. Simple Display: The displayWidget() method outputs the necessary HTML and JavaScript for the reCAPTCHA widget.

  5. Easy Verification: The verifyResponse() method handles the server-side verification of the reCAPTCHA response.

How to Use the Wrapper

In Your HTML Form

Here's how you can use the wrapper in your HTML form:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Form with reCAPTCHA</title>
    </head>
    <body>
        <form action="verify.php" method="post">
            <input type="text" name="name" placeholder="Enter your name" required>
            <?php
                require_once 'ReCaptchaWrapper.php';
            
                // Optionally override default keys
                ReCaptchaWrapper::init('your_site_key', 'your_secret_key');
                
                ReCaptchaWrapper::displayWidget();
            ?>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

Verifying the Response

In your PHP script that handles the form submission:

<?php

require_once 'ReCaptchaWrapper.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Optionally override default keys
    ReCaptchaWrapper::init('your_site_key', 'your_secret_key');

    $response = $_POST['g-recaptcha-response'];

    if (ReCaptchaWrapper::verifyResponse($response)) {
        echo 'Form submission successful!';

        // Process form data...
    } else {
        echo 'reCAPTCHA verification failed. Please try again.';
    }
}

Conclusion

This simple PHP wrapper for Google reCAPTCHA provides an easy and flexible way to integrate reCAPTCHA into your web forms. By using static methods and allowing for default keys with the option to override, it offers a balance of simplicity and customization.

Remember to replace the default keys in the class with your actual reCAPTCHA keys for production use. Happy coding, and keep those bots at bay!

Support My Work

If you enjoy my content, consider supporting me through Buy Me a Coffee or GitHub Sponsors.

Buy Me A Coffee
or

More posts

Building a Dynamic Dropdown Menu with Alpine.js

Learn how to create a dynamic dropdown menu using Alpine.js. This tutorial covers basic implementation, enhancing with styling and accessibility, and leveraging Alpine.js features like x-data, x-show, and transition effects for a sleek user interface.

Supercharge Your Laravel App Monitoring with Laravel Pulse

Laravel Pulse is a free, open-source performance monitoring tool for Laravel apps. It offers features like user activity tracking, server statistics, queue monitoring, and slow query detection. Use Pulse for performance optimization, user experience improvement, resource allocation, and error tracking. Best practices include securing the dashboard, considering dedicated databases for high-traffic apps, and regularly reviewing insights.