用PHP搭配Cloudflare Turnstile CAPTCHA
網路上有許多機器人驗證的替代方案,這裡介紹與 Google reCAPTCHA 寫法幾乎一樣的 Turnstile 給大家嘗試看看。 下面的寫法給各位參考: 後端PHP傳送與接收資料 與 Google 一樣,將query「response」與「secret」丟過去就可以了(範例多了「remoteip」,這個不一定要有)。 // captcha.php $captcha = $_POST['cf-turnstile-response']; $secretKey = 'your_secret_key'; $ip = $_SERVER['REMOTE_ADDR']; $url_path = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; $data = array('secret' => $secretKey, 'response' => $captcha, 'remoteip' => $ip); $opts = array( 'http'=> array( 'method'=> 'POST', 'content'=> http_build_query($data) ) ); $query = stream_context_create($opts); $result = file_get_contents($url_path, false, $query); echo json_encode($result); // 如果你想在後端直接判斷有沒有成功 $array = json_decode($result, true); $success = $array['success']; if($success){ // 驗證成功 }else{ // 驗證失敗 } 後端PHP這樣寫沒有問題,但資料回傳到前端JavaScript問題就出現了。 前端JavaScript接收Object $.ajax({ type: ...