middlewares / recaptcha
Middleware to use Google reCAPTCHA for spam prevention
Installs: 31 673
Dependents: 0
Suggesters: 0
Security: 0
Stars: 6
Watchers: 2
Forks: 0
Open Issues: 1
Requires
- php: ^7.2 || ^8.0
- google/recaptcha: ^1.1
- middlewares/utils: ^3.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^2.3
- oscarotero/php-cs-fixer-config: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^8|^9
- squizlabs/php_codesniffer: ^3.0
README
Middleware to use google/recaptcha library for spam prevention. Returns a 403
response if the request is not valid. More info about Google reCAPTCHA.
Requirements
- PHP >= 7.2
- A PSR-7 http library
- A PSR-15 middleware dispatcher
Installation
This package is installable and autoloadable via Composer as middlewares/recaptcha.
composer require middlewares/recaptcha
Example
$dispatcher = new Dispatcher([ new Middlewares\Recaptcha($secretKey), //in your view function () { echo '<div class="g-recaptcha" data-sitekey="XXX"></div>'; echo '<script type="text/javascript" src="https://www.google.com/recaptcha/api.js"></script>'; } ]); $response = $dispatcher->dispatch(new ServerRequest());
Usage
You need a secret API key for your app. You can register it at https://www.google.com/recaptcha/admin
$secretKey = 'Your-Secret-Key'; $recaptcha = new Middlewares\Recaptcha($secretKey);
Optionally, you can provide a Psr\Http\Message\ResponseFactoryInterface
as the second argument to create the error responses (403
). If it's not defined, Middleware\Utils\Factory will be used to detect it automatically.
$responseFactory = new MyOwnResponseFactory(); $recaptcha = new Middlewares\Recaptcha($secretKey, $responseFactory);
ipAttribute
By default uses the REMOTE_ADDR
server parameter to get the client ip. This option allows to use a request attribute. Useful to combine with a ip detection middleware, for example client-ip:
$dispatcher = new Dispatcher([ //detect the client ip and save it in "ip" attribute (new Middlewares\ClientIP())->attribute('ip'), //use that attribute (new Middlewares\Recaptcha($secretKey))->ipAttribute('ip') ]);
Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.
The MIT License (MIT). Please see LICENSE for more information.