Skip to content

Instantly share code, notes, and snippets.

@jonathansanchez
Created March 6, 2018 16:46
Show Gist options
  • Save jonathansanchez/7f09242cf8c05fb67f42367e6caef6d0 to your computer and use it in GitHub Desktop.
Save jonathansanchez/7f09242cf8c05fb67f42367e6caef6d0 to your computer and use it in GitHub Desktop.
Server side validation ReCaptcha
<?php
use App\Exceptions\Validator;
$input = $request->all(); //For example in Laravel
if ($request->method() === 'POST') {
if ( !Validator::captcha($input['g-recaptcha-response']) ) {
return "Invalid Captcha :(";
}
return "Validated :)";
}
<?php
namespace App\Exceptions;
/**
* Class Validator to sanitize
* manually fields from Request.
* @package App\Exceptions
*/
class Validator extends \Exception
{
const CAPTCHA_SECRET = YOUR-SECRET-KEY;
const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
/**
* Validate a Re Captcha.
*
* @param $token
* @return bool
*/
public static function captcha($token)
{
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$postData = http_build_query([
'secret' => self::CAPTCHA_SECRET,
'response' => $token,
'remoteip' => $_SERVER['REMOTE_ADDR']
]);
$opts = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postData
]
];
$context = stream_context_create($opts);
$response = file_get_contents(self::VERIFY_URL, false, $context);
$result = json_decode($response);
if (!$result->success) {
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment