Single File ReCaptcha 2 PHP Client

leading captcha system, curl, php, json-response

Today, a web-form without a proven captcha system generates a lot of spam entries and data-trash in your database. One of the best is ReCaptcha (even the latest v2).

Google provides an easy to use ReCaptcha PHP Client – but it’s a bit over engineered! You need a bunch of PHP files and a composer based environment to use it out of the box. This can cause some trouble in highly customized/optimized projects.

Therefore, here is a “one-file” solution which works without any configuration overhead:

Usage#

require('ReCaptcha.php');

// register your secret
ReCaptcha::setSecret('<your-secret>');

// some code ...

// check user form
if (ReCaptcha::isValid()){ ...

One-File Solution#

// Developer Guide: https://developers.google.com/recaptcha/docs/verify
class ReCaptcha{

    // ReCaptcha API Endpoint
    const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';

    // the last result
    private static $_result = null;

    // client secret
    private static $_secret = null;

    // validate
    public static function isValid(){
        // token available ?
        if (!isset($_POST['g-recaptcha-response'])){
            return false;
        }

        // extract token
        $token = trim($_POST['g-recaptcha-response']);

        // generate url
        $params = http_build_query(array(
            'secret' => self::$_secret,
            'response' => $token,
            'remoteIp' => $_SERVER['REMOTE_ADDR']
        ), '', '&');

        // create curl based post request
        $handle = curl_init(self::SITE_VERIFY_URL);
        $options = array(
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $params,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),
            CURLINFO_HEADER_OUT => false,
            CURLOPT_HEADER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true
        );
        curl_setopt_array($handle, $options);
        $response = curl_exec($handle);
        curl_close($handle);

        // decode response
        self::$_result = json_decode($response, true);

        // check
        return (self::$_result['success'] === true);
    }

    // error occurred ?
    public static function isError(){
        return (self::$_result['success'] === false);
    }

    // get error message from last request
    public static function getErrorMessages(){
        return self::$_result['error-codes'];
    }

    // set client secret
    public static function setSecret($s){
        self::$_secret = $s;
    }
}