Consent

This site uses third party services that need your consent.

Skip to content
Steven Roland
  • Creating a Simple PHP Wrapper for Google reCAPTCHA

    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!

    More posts

    Simple PHP CSRF Token

    CSRF tokens, or anti-CSRF tokens, are a security measure used to prevent Cross-Site Request Forgery (CSRF) attacks. They work by ensuring that a submitted request is only accepted by a web application if it contains a string that the server expects.