woff 發表於 2021-11-7 22:10:38

Google reCAPTCHA V2 機器人驗證 教學 PHP範例

如果已經註冊過,想查詢自己的公私鑰:
https://www.google.com/recaptcha/admin#list
還沒註冊過的,下面三步驟建立Google reCAPTCHA~

STEP I前往 Google機器人官網,點選右上的 「Admin console」按鈕。

STEP II填入名稱、選擇驗證類型、網域、管理者,同意Google蒐集網頁資訊、建立選1.勾選我不是機器人



STEP III



下方則是貼到要顯示的位置<div id="recaptcha_box2"></div>這段代碼接到網站<head>裡面<!-- Google reCAPTCHA -->
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback2&render=explicit" async></script>               
        <script>
      var onloadCallback2 = function() {
      grecaptcha.render("recaptcha_box2", {
      /* Change Your sitekey */
      "sitekey": "公鑰",
      "callback": callback2
      });
      };

      function callback2() {
      /* 這裡可執行提交表單的動作
      alert("恭喜你驗證成功");
      */
      document.getElementById("submit2").disabled = false;
      document.getElementById("submit2").classList.remove('au-btn--gray');
      document.getElementById("submit2").classList.add('au-btn--yellow');
      }
    </script>
PHP驗證版// GOOGLE RECAPTHA
        $data['secret'] = '私鑰';
    $data['response'] = $_POST['g-recaptcha-response'];
    $ch = curl_init();
    // 使用CURL驗證
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    $result = curl_exec($ch);
    curl_close($ch);
    // 解密
        $result = json_decode($result, true);

    // 檢查是否通過驗證
    if ( ! isset($result['success']) || ! $result['success']) {
      // 驗證失敗
                echo "<script>alert('驗證碼機器人失敗!');history.go(-1);</script>";
                exit;
    }

然後在form的action程式裏面貼上使用這個function ,如果false就不給登入,就可以啦~查詢建立好的公私鑰: https://www.google.com/recaptcha/admin/site/350731086/settings

文章出處


頁: [1]
查看完整版本: Google reCAPTCHA V2 機器人驗證 教學 PHP範例