jrobinsonc
10/19/2016 - 9:53 PM

reCaptcha

reCaptcha

<?php

class reCaptcha
{
    private $key;
    private $secret;

    public function __construct($key, $secret)
    {
        $this->key = $key;
        $this->secret = $secret;
    }

    public function getWidgetHTML()
    {
        return '<script src="//www.google.com/recaptcha/api.js" async defer></script>'
        . '<div class="g-recaptcha" data-sitekey="'. $this->key .'"></div>';
    }

    public function validateResponse()
    {
        if ( ! isset( $_POST['g-recaptcha-response'] ) || $_POST['g-recaptcha-response'] === '' ) {
            return null;
        }

        $req = http_build_query([
            'secret' => $this->secret,
            'response' => $_POST['g-recaptcha-response'],
            // 'remoteip' => $_SERVER['REMOTE_ADDR'],
        ]);

        $json = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, stream_context_create(array(
            'http' => array(
                'method'  => 'POST',
                'header'  => implode('\r\n', [
                    'Content-type: application/x-www-form-urlencoded',
                    'User-Agent: reCAPTCHA/PHP',
                    'Content-Length: '. strlen($req),
                ]),
                'content' => $req
            )
        )));

        $res = json_decode($json, true);

        if ( ! is_array( $res ) || ! isset( $res['success'] ) || false === $res['success'] ) {
            return false;
        }

        return true;
    }

}

reCaptcha

Usage

<?php

$recaptcha = new reCaptcha(reCAPTCHA_KEY, reCAPTCHA_SECRET_KEY);

if ($_POST) {
  $validate = $recaptcha->validateResponse();

  if (null === $validate) {
      echo "The captcha field is empty.";
  } else if (false === $validate) {
      echo "The captcha field is not valid.";
  } else if (true === $validate) {
      echo "Success.";
  }
}

<form>
<?php echo $recaptcha->getWidgetHTML(); ?>
<input type="submit">
</form>