Created
March 6, 2018 16:46
-
-
Save jonathansanchez/7f09242cf8c05fb67f42367e6caef6d0 to your computer and use it in GitHub Desktop.
Server side validation ReCaptcha
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 :)"; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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