PHP 8.6表单接入Turnstile后,必须把浏览器提交的令牌发送到Siteverify,并同时检查success、hostname和预期action。客户端显示验证完成并不足以放行业务请求;令牌有效期为300秒,服务端验证失败或网络结果未知时都应停止处理当前表单。
前端与后端使用同一组站点配置
使用php 8.6 cli和curl扩展。下面的requestjson辅助函数保存为同目录的http.php;调用方从环境变量读取已获得相应权限的令牌,不把令牌写入源码。http错误由业务脚本检查,网络超时不会自动重发写请求。
<?php function requestJson(string $method, string $url, array $headers = [], ?array $data = null): array {
$ch = curl_init($url);
$headers[] = 'Accept: application/json';
$options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers, CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 45, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS];
if ($data !== null) {
$headers[] = 'Content-Type: application/json';
$options[CURLOPT_HTTPHEADER] = $headers;
$options[CURLOPT_POSTFIELDS] = json_encode($data, JSON_THROW_ON_ERROR);
}
curl_setopt_array($ch, $options);
$raw = curl_exec($ch);
if ($raw === false) { throw new RuntimeException('Network request failed'); }
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$status, $raw === '' ? [] : json_decode($raw, true, 512, JSON_THROW_ON_ERROR)];
}
先在Turnstile控制台创建站点,前端widget设置固定action,例如contact,并把cf-turnstile-response随表单提交。下面后端示例使用全球Siteverify域名;中国域名widget按官方要求改用challenges.cloudflare-cn.com,密钥和站点必须匹配。

Siteverify请求中的secret和response字段
只在字段绑定检查通过后放行
<?php require __DIR__.'/http.php';
$token=$_POST['cf-turnstile-response']??'';
if(!is_string($token)||$token===''||strlen($token)>2048){http_response_code(400);exit;}
try{
[$status,$r]=requestJson('POST','https://challenges.cloudflare.com/turnstile/v0/siteverify',[],[
'secret'=>getenv('TURNSTILE_SECRET')?:throw new RuntimeException('Missing secret'),
'response'=>$token
]);
$allowed=$status===200 && ($r['success']??false)===true
&& ($r['hostname']??'')==='forms.example.com'
&& ($r['action']??'')==='contact';
}catch(Throwable $e){http_response_code(503);exit('Verification unavailable');}
if(!$allowed){http_response_code(400);exit('Refresh verification');}
// Continue with the normal authenticated form handler.
echo 'Verification accepted';

验证结果中的hostname与action字段
令牌通过后仍要做表单自身的防重
将forms.example.com替换为实际允许的域名,不能把浏览器提交的hostname或action当作预期值。timeout-or-duplicate可能表示过期或重复使用,应让widget重新取得令牌。网络失败可使用同一idempotency_key安全重试验证请求,但不能在结果未知时当作成功。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
官方说明令牌兑付状态存在网络收敛窗口,“单次使用”不等于所有节点立即看到重复。提交订单、发邮件或创建工单仍需独立的业务请求ID和唯一约束;Siteverify也不替代CSRF校验、权限和参数校验。

单次使用令牌与网络收敛的限制
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










