Simplest Cloudflare Turnstile Code in PHP
Follow the guide here:
Cloudflare Turnstile - Client-Side Rendering
Important Point:
Once a Turnstile token fails, it cannot be reused.
This means that if a login attempt fails (e.g., due to an incorrect password), you must reset Turnstile using:
turnstile.reset(widgetId);
If you don’t reset it, the old (failed) token will remain invalid. So, even if you enter the correct password on the next attempt, the login will still fail because Turnstile won’t generate a new token.
To avoid this issue, always reset Turnstile after a failed login attempt.
<form action="/path/authentication/index.php" class="signin-form clearfix" id="signup" method="post">
...
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" defer></script>
<div style="max-width: 100%; margin-right: auto; margin-left: auto; height: 65px;">
<div class="cf-turnstile" data-sitekey="0x4AAAAAAA7OP_XX-yyyyZZZ" data-size="flexible" data-language="<?= t(['en', 'ko', 'ja']); ?>" data-theme="light" data-callback="tsSuccess"></div>
</div>
...
<button ... >Login</button>
</form>
$('form.signin-form').submit(function() {
$form = $(this);
...
$.post($form.attr('action'), $form.serializeArray(), function(json) {
if ( json.status == 1 ) {
// Logged In!
window.location.href = 'redirect_some_where';
} else {
const cloudFlareTurnstileEl = document.querySelector("[name='cf-turnstile-response']",);
// cloudFlareTurnstileEl.id => cf-chl-widget-xxx99_response
if ( cloudFlareTurnstileEl?.id ) {
// widgetId: cf-chl-widget-xxx99
const widgetId = cloudFlareTurnstileEl?.id?.replace('_response', '');
// Reset Turnstile
// turnstile.reset() is in loaded script, https://challenges.cloudflare.com/turnstile/v0/api.js
turnstile.reset(widgetId);
}
}
...
}, "json");
});
$cft = $_POST('cf-turnstile-response');
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://challenges.cloudflare.com/turnstile/v0/siteverify",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'secret' => '0x4AAAAAAA7OPxxxxxxxxxx_yyyy-zzzzzz',
'response' => $cft
], "", "&")
]);
$response = curl_exec($curl);
if ( @$response ) {
$res = json_decode($response, true);
if ( !@$res['success'] ) {
echo 'Failed_JSON_Code';
exit;
} else {
echo 'Succeed_JSON_Code';
exit;
}
}
Responses
Leave a response to @richard