PHP code example of oppara / cakephp-turnstile

1. Go to this page and download the library: Download oppara/cakephp-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/ */

    

oppara / cakephp-turnstile example snippets


bin/cake plugin load Oppara/Turnstile

[
    'siteKey' => getenv('TURNSTILE_SITE_KEY') ?: null,
    'secretKey' => getenv('TURNSTILE_SECRET_KEY') ?: null,
    'verifyUrl' => 'https://challenges.cloudflare.com/turnstile/v0/siteverify',
    'timeout' => 5,
    'responseFieldName' => 'cf-turnstile-response',
]

public function initialize(): void
{
    parent::initialize();

    $this->loadHelper('Turnstile.Turnstile');
}

echo $this->Turnstile->script();
echo $this->Turnstile->widget([
    'theme' => 'light',
    'size' => 'flexible',
]);

echo $this->Turnstile->render([
    'theme' => 'light',
]);

echo $this->Turnstile->script(['nonce' => $cspNonce]);

public function initialize(): void
{
    parent::initialize();

    $this->loadComponent('Turnstile.Turnstile');
}

use Oppara\Turnstile\Exception\TurnstileException;
use Psr\Log\LogLevel;

try {
    $success = $this->Turnstile->verify();
} catch (TurnstileException $e) {
    // Infrastructure / configuration error — not the user's fault.
    $this->log('Turnstile: ' . $e->getMessage(), LogLevel::ERROR);
    $this->Flash->error(__('Verification is temporarily unavailable. Please try again later.'));

    return $this->redirect(['action' => 'index']);
}

if (!$success) {
    // Cloudflare rejected the challenge — typically a user-side issue
    // (expired token, replayed token, unsolved challenge, …).
    $errors = $this->Turnstile->getResult()['error-codes'] ?? [];
    $this->log(
        sprintf('Turnstile rejected the challenge: %s', json_encode($errors)),
        LogLevel::WARNING,
    );
    $this->Flash->error(__('The challenge could not be verified. Please try again.'));

    return $this->redirect(['action' => 'index']);
}

// Verification passed — continue with the normal form handling.

$success = $this->Turnstile->verify(
    (string)$this->request->getData('cf-turnstile-response'),
    $this->request->clientIp(),
);