PHP code example of ikeda / php-captcha-for-recaptcha-v3
1. Go to this page and download the library: Download ikeda/php-captcha-for-recaptcha-v3 library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ikeda / php-captcha-for-recaptcha-v3 example snippets
namespace App\Providers;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\HtmlString;
use Illuminate\Support\ServiceProvider;
use PiCaptcha\Captcha;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(Captcha::class, static fn (Application $app): Captcha => new Captcha($app['config']['captcha']['secret']));
}
public function boot(): void
{
Blade::directive('captchaScript', static fn (string $expression): Htmlable => new HtmlString(Captcha::js($expression)));
}
}
namespace App\Http\Controllers\Captcha;
use PiCaptcha\Captcha;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class VerifyTokenController
{
private Captcha $captcha;
public function __construct(Captcha $captcha)
{
$this->captcha = $captcha;
}
public function __invoke(Request $request): JsonResponse
{
$action = $request->input('action');
$token = $request->input('token');
$hostname = $request->getHost();
$clientIp = $request->getClientIp();
$result = $this->captcha->verify(token: $token, clientIp: $clientIp, action: $action, score: 0.1, hostname: $hostname)
return new JsonResponse((object) ['success' => $result->isSuccess()]);
}
}
<?
use Illuminate\Support\Facades\Route;
Route::get('/captcha/verify', App\Http\Controllers\Captcha\VerifyTokenController::class)->name('captcha.verify');
<x-sample-layout>
<script>
grecaptcha.ready(() => {
grecaptcha.execute(`{{ config('captcha.site_key') }}`, { action: 'examples/recaptcha' }).then((token) => {
fetch(`{{ route('captcha.verify') }}?action=examples/recaptcha&token=${token}`).then((response) => {
response.json().then((data) => {
if (data.success) {
// Add your logic to submit to your backend server here.
}
});
});
});
});
</script>
<div>
<from>
<!-- ... -->
</form>
</div>
</x-sample-layout>