CodeIgniter 4 package for integrating Cloudflare Turnstile Captcha
MIT License
CI4CFTurnstile is a CodeIgniter 4 library that integrates Cloudflare's Turnstile CAPTCHA for form validation. It supports both implicit and explicit rendering modes.
You can find the document of Cloudflare Turnstile here.
Install the package via Composer:
composer require davodm/codeigniter4-turnstile
After installation, configure your Cloudflare Turnstile site and secret keys. You can do this by setting the environment variables in your .env file:
turnstile.siteKey=your-site-key
turnstile.secretKey=your-secret-key
The library provides helper functions turnsitle
to render the CAPTCHA in your views: turnstile_implicit()
, turnstile_explicit()
, and turnstile_explicit_render()
.
In your view file, you can render the Turnstile CAPTCHA in implicit mode by calling:
helper('turnstile');
echo turnstile_implicit('turnstile_field_name', 'auto', 'normal');
For explicit mode, you need to follow these steps:
helper('turnstile');
turnstile_explicit('turnstile_field_name', 'dark', 'normal');
<div id="turnstile_field_name"></div>
<?= turnstile_explicit_render(); ?>
To validate the CAPTCHA response, you can use the TurnstileRules validation rule in your controller or model.
First, register the validation rule in your validation configuration file (app/Config/Validation.php
):
public $ruleSets = [
// other rules
\CI4CFTurnstile\Validation\TurnstileRules::class,
];
Then, in your form validation logic:
$validation = \Config\Services::validation();
$validation->setRules([
'turnstile_field_name' => 'required|turnstile_verify',
]);
if (!$validation->withRequest($this->request)->run()) {
// Handle validation errors
$errors = $validation->getErrors();
// Display errors to the user
}
Here’s a complete example of using CI4CFTurnstile in a controller:
namespace App\Controllers;
use CodeIgniter\Controller;
class FormController extends Controller
{
public function index()
{
helper('turnstile');
return view('form');
}
public function submit()
{
$validation = \Config\Services::validation();
$validation->setRules([
'turnstile_field_name' => 'required|turnstile_verify',
]);
if (!$validation->withRequest($this->request)->run()) {
return redirect()->back()->withInput()->with('errors', $validation->getErrors());
}
// CAPTCHA passed
// Proceed with form processing
}
}
In your form.php view file:
<!-- Implicit form model -->
<form method="post" action="/form/submit">
<!-- Other form fields -->
<?= turnstile_implicit('turnstile_field_name'); ?>
<button type="submit">Submit</button>
</form>
<!-- Explicit form model -->
<form method="post" action="/form/submit">
<!-- Other form fields -->
<div id="turnstile_field_name"></div>
<?= turnstile_explicit('turnstile_field_name', 'dark', 'normal'); ?>
<button type="submit">Submit</button>
</form>
<?=turnstile_explicit_render?>
</body>
This project is licensed under the MIT License - see the License file for details.
Davod Mozafari - Twitter