Skip to content

Instantly share code, notes, and snippets.

@dnetix
Created February 7, 2015 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnetix/a5d17847b75153a0fb86 to your computer and use it in GitHub Desktop.
Save dnetix/a5d17847b75153a0fb86 to your computer and use it in GitHub Desktop.
<?php
/**
* Class ReCaptcha
*
* USAGE:
*
* CLIENT SIDE:
* Create the tags like its explained on the google site when you obtain the keys or before the </head> tag
* <?= ReCaptcha::getHeadTag() ?> and where you want to put the verification <?= ReCaptcha::getFormTag() ?>
*
* SERVER SIDE:
* Just need an if(ReCaptcha::check($_POST['g-recaptcha-response']) an it returns true when verified, and false
* when not verified, if you want to check the errors just do a ReCaptcha::getErrors()
*
*/
class ReCaptcha {
public $status = false;
public $errors = [];
const SITE_KEY = '';
const SECRET_KEY = '';
const URL_SCRIPT = 'https://www.google.com/recaptcha/api.js';
const URL_VERIFY = 'https://www.google.com/recaptcha/api/siteverify';
private static $INSTANCE;
private function __construct($status = false, $errors = []){
$this->status = $status;
$this->errors = $errors;
}
public static function check($response, $remoteIp = null){
if(empty($response)){
self::$INSTANCE = new self(false, ['No input given']);
return false;
}
if(empty($remoteIp)){
$remoteIp = $_SERVER['REMOTE_ADDR'];
}
$HTTPData = self::getHTTPData($response, $remoteIp);
if($HTTPData->success){
return true;
}else{
self::$INSTANCE = new self(false, $HTTPData->error-codes);
return false;
}
}
public static function getErrors(){
if(empty(self::$INSTANCE)){
return "Not checked yet";
}else{
return implode(', ', self::$INSTANCE->errors);
}
}
private static function submitHTTP($response, $remoteIp){
return file_get_contents(self::URL_VERIFY.'?'.http_build_query([
'secret' => self::SECRET_KEY,
'response' => $response,
'remoteip' => $remoteIp
]));
}
private static function getHTTPData($response, $remoteIp){
$httpResponse = self::submitHTTP($response, $remoteIp);
if($httpResponse === false){
return null;
}else{
return json_decode($httpResponse);
}
}
public static function getFormTag(){
return '<div class="g-recaptcha" data-sitekey="'.self::SITE_KEY.'"></div>';
}
public static function getHeadTag(){
return '<script src="'.self::URL_SCRIPT.'"></script>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment