1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPを使ったWebサイトのフォームにreCAPTCHA v3を導入する

Posted at

今回の記事では、HTMLとPHPで作られたフォームにreCAPTCHA v3を導入する方法を解説していきます。

reCAPTCHAの管理画面を開く

reCAPTCHAのページから管理画面にアクセスします。

Screenshot 2024-10-14 at 1.32.30.png

サイトのURLを登録

ラベルを設定してサイトのドメインを登録します。

Screenshot 2024-10-14 at 1.33.03.png

サイトキーとシークレットキーを取得

設定を開いてください。

Screenshot 2024-10-14 at 1.38.07.png

サイトキーとシークレットキーをコピーします。

Screenshot 2024-10-14 at 1.38.32.png

reCAPTCHAを導入するための準備はこれでOKです。

head内にreCAPTCHAのスクリプトを入れる

index.html
<script src="https://www.google.com/recaptcha/api.js?render=ここにサイトキー"></script>

フォーム内にinputタグを追加

index.html
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">

フォームのHTMLファイルにJavaScriptのコードを追加

index.html
<script>
  grecaptcha.ready(function() {
      grecaptcha.execute('ここにサイトキー', {action: 'submit'}).then(function(token) {
          var recaptchaResponse = document.getElementById('recaptchaResponse');
          recaptchaResponse.value = token;
      });
  });
</script>

送信先のPHPファイルにreCAPTCHAスコアを判定する処理を入れる

form.php
// reCAPTCHAのシークレットキー
$secretKey =  'ここにシークレットキー';

// reCAPTCHAのレスポンス
$recaptcha_response = $_POST['recaptcha_response'];

// APIリクエスト
$verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$recaptcha_response}");

// APIレスポンス確認
$responseData = json_decode($verifyResponse);

if ($responseData->score < 0.2) {
    $score = isset($responseData->score) ? $responseData->score : 'No Score';
    echo "invalid request: {$score}<br>"; // 失敗
    exit; // 処理を停止
}

今回は以上です。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?