PHP code example of siberfx / cloudflare-turnstile
1. Go to this page and download the library: Download siberfx/cloudflare-turnstile 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/ */
siberfx / cloudflare-turnstile example snippets
use Siberfx\Turnstile\Rules\Turnstile;
$request->validate([
'email' => ['
use Illuminate\Validation\Rule;
'cf-turnstile-response' => [Turnstile::action('login')],
// or
'cf-turnstile-response' => [Rule::turnstile('login')],
Route::post('/contact', ContactController::class)->middleware('turnstile');
Route::post('/login', LoginController::class)->middleware('turnstile:login');
use Siberfx\Turnstile\Facades\Turnstile;
$result = Turnstile::verify(
token: $request->input('cf-turnstile-response'),
remoteIp: $request->ip(),
action: 'checkout', // optional
);
if ($result->fails()) {
logger()->warning('Turnstile failed', $result->toArray());
}
$result->hostname; // "example.com"
$result->action; // "checkout"
$result->cdata; // custom data from the widget
$result->challengedAt; // DateTimeImmutable
$result->ephemeralId; // Enterprise only
$result->errors(); // list<ErrorCode>
use Siberfx\Turnstile\Enums\ErrorCode;
use Siberfx\Turnstile\Facades\Turnstile;
it('sends the contact form', function () {
Turnstile::fake();
$this->post('/contact', ['cf-turnstile-response' => 'any'])->assertRedirect();
Turnstile::assertVerified('any');
});
it('rejects bots', function () {
Turnstile::fake(passes: false);
// or: Turnstile::fake()->fail(ErrorCode::TimeoutOrDuplicate);
$this->post('/contact')->assertSessionHasErrors('cf-turnstile-response');
});
bash
php artisan turnstile:publish # add --force to overwrite existing files
# equivalent to: php artisan vendor:publish --tag=turnstile
bash
php artisan vendor:publish --tag=turnstile-config
php artisan vendor:publish --tag=turnstile-views
php artisan vendor:publish --tag=turnstile-lang
blade
<form method="POST" action="/contact">
@csrf
<!-- ... -->
<x-turnstile />
@error('cf-turnstile-response')
<p class="text-red-600">{{ $message }}</p>
@enderror
<button type="submit">Send</button>
</form>
blade
<x-turnstile
theme="dark" {{-- auto | light | dark --}}
size="flexible" {{-- normal | flexible | compact --}}
appearance="interaction-only"
language="tr"
action="login"
cdata="user-42"
callback="onTurnstileSuccess"
error-callback="onTurnstileError"
expired-callback="onTurnstileExpired"
id="captcha"
class="mt-4"
/>