PHP code example of wolfcode / cloudflare-turnstile

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

    

wolfcode / cloudflare-turnstile example snippets


use Wolfcode\CloudflareTurnstile\Widget;

$widget = new Widget(
    siteKey: 'YOUR_SITE_KEY',
);
echo $widget->render();

use Wolfcode\CloudflareTurnstile\Turnstile;
use Wolfcode\CloudflareTurnstile\Exception\ValidationException;

$turnstile = new Turnstile(
    secretKey: 'YOUR_SECRET_KEY',
);

try {
    $result = $turnstile->validate($_POST['cf-turnstile-response']);
    // Validation passed
} catch (ValidationException $e) {
    // Validation failed
    echo $e->getMessage();
}

use GuzzleHttp\Client;
use Wolfcode\CloudflareTurnstile\Turnstile;

$client = new Client([
    'proxy' => 'tcp://localhost:8080',
    'timeout' => 30,
]);

$turnstile = new Turnstile(
    secretKey: 'YOUR_SECRET_KEY',
    client: $client,
);

if ($turnstile->isValid($_POST['cf-turnstile-response'])) {
    // Valid token
}

$token = Turnstile::getToken();
$remoteIp = Turnstile::getRemoteIp();

$widget = new Widget(siteKey: 'YOUR_SITE_KEY');
echo $widget->render();

echo $widget->render(action: 'login');

echo $widget->render(data: 'session-12345');

echo $widget->renderComplete();

use Wolfcode\CloudflareTurnstile\Exception\ValidationException;

try {
    $turnstile->validate($token);
} catch (ValidationException $e) {
    $errorCodes = $e->getErrorCodes();
    
    foreach ($errorCodes as $code) {
        match ($code) {
            'missing-input-response' => // Token not provided
            'invalid-input-response' => // Invalid or expired token
            'timeout-or-duplicate' => // Token already used
            'hostname_mismatch' => // Hostname doesn't match
            'action_mismatch' => // Action doesn't match
            default => // Unknown error
        };
    }
}