如何让file_get_contents适配Cloudflare Turnstile站点验证?
Cloudflare Turnstile验证405错误的解决办法
你的操作确实有误,不是Cloudflare封禁了file_get_contents,而是Cloudflare Turnstile的siteverify接口只接受POST请求,但你现在用的是GET请求(把secret和response拼在URL里,file_get_contents默认发送GET请求),这才导致了405 Method Not Allowed错误。之前Google reCAPTCHA和hCaptcha的验证接口支持GET,所以那套代码能正常运行,但Turnstile不支持这种方式。
你完全可以继续用file_get_contents,只要改成POST请求即可,具体代码如下:
$secret = 'SECRET KEY'; $captcha = $_POST['cf-turnstile-response']; // 构造POST请求参数 $postData = http_build_query([ 'secret' => $secret, 'response' => $captcha ]); // 创建请求上下文,指定POST方法和请求头 $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => $postData ] ]); // 发送POST请求验证 $verifyUrl = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; $response = file_get_contents($verifyUrl, false, $context); $responseData = json_decode($response); if ($responseData->success == true) { // 验证通过,处理表单逻辑 } else { // 验证失败,拒绝处理表单 }
如果觉得file_get_contents在复杂场景下不够稳定,也可以用cURL实现,代码示例如下:
$secret = 'SECRET KEY'; $captcha = $_POST['cf-turnstile-response']; $ch = curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'secret' => $secret, 'response' => $captcha ])); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $responseData = json_decode($response); if ($responseData->success == true) { // 验证通过,处理表单 } else { // 验证失败 }
内容的提问来源于stack exchange,提问作者DumbDumbStack
相关产品推荐
相关产品推荐

