Ga naar inhoud

Blog

Laravel - Integrate reCAPTCHA

To integrate a simple reCAPTCHA into my contact form i preffer to use my own code instead of some third party library.

Register your site

reCAPTCHA: Easy on Humans, Hard on Bots

Config

Create file in 'config/recaptcha.php'

return [ 'sitekey' => 'your-sitekey-here', 'secretkey' => 'your-secretkey-here' ];

Class

Create file in 'app/Classes/Recaptcha.php'

<?php namespace App\Classes; class Recaptcha { const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'; public $secret; public $response; public $remoteip; public function verify() { $postfields = [ 'secret' => $this->secret, 'response' => $this->response, 'remoteip' => ($this->remoteip == '::1' ? '127.0.0.1' : $this->remoteip) ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, self::SITE_VERIFY_URL); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, CURLINFO_HEADER_OUT, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); $response = curl_exec($ch); curl_close($ch); $oResponse = json_decode($response); return $oResponse->success; } }

Add to autoloader in 'composer.json'

"autoload": { "files": [ "app/Classes/Recaptcha.php" ] }

Finnaly we need to regenerate ('vender\composer\autoload_classmap.php') the list of all classes that need to be included:

composer dump-autoload

View

Add script to template or view

<script src="//www.google.com/recaptcha/api.js"></script>

Add div -tag within <form> ... </form>

<div class="g-recaptcha" data-sitekey="{{ Config::get('recaptcha.sitekey') }}"></div>

Controller

use Config; use App\Classes\Recaptcha;

Check if POST data is not empty

$aMessages = [ 'g-recaptcha-response.required' => trans('messages.required', ['name' => 'reCAPTCHA']) ]; $oValidator = Validator::make(Input::all(), [ 'g-recaptcha-response' => 'required' ], aMessages); if ($oValidator->fails()) { $aErrors = $oValidator->errors(); }

Check if reCAPTCHA is valid

if ( ! count($aErrors)) { $oRecaptcha = new Recaptcha; $oRecaptcha->secret = Config::get('recaptcha.secretkey'); $oRecaptcha->response = Input::get('g-recaptcha-response'); $oRecaptcha->remoteip = $request->getClientIp(); if ( ! $oRecaptcha->verify()) { $aErrors['g-recaptcha-response'] = trans('messages.invalid', ['name' => 'reCAPTCHA']); } }

Messages (optional)

Edit file 'resources\lang\en\messages.php':

return [ 'required' => ':name is required.', 'invalid' => ':name is invalid.' ];
Urls