reCAPTCHA認証

準備

キー取得

reCAPTCHAのサイト登録のページでキーを取得
https://www.google.com/recaptcha/admin


googleのアドレスでないといけない
xamppで実行する場合のアドレスは「127.0.0.1」
URLもlocalhostでなく127.0.0.1/~でないとエラーとなる
※xamppでもバーチャルホストにてドメインを設定した場合はそのドメインで使用可

実装

クライアント側

<html>
<head>
<script src=”https://www.google.com/recaptcha/api.js” async defer></script>
<script>
 function validateRecaptcha ( code ) {
  if ( !!code ) {
   var form = document.querySelector(“.recaptcha“);
   form.removeAttribute(‘disabled’);
  }
 }
</script>
</head>
<body>

<form action=”server.php” method=”post” enctype=”multipart/form-data”>
  <div
   class=”g-recaptcha
   data-callback=”validateRecaptcha”
   キー取得で取得したSiteKeyを設定
   data-sitekey=”XXXXXXXXXXXXXXXXXXXX“>
  </div>

  <input name=”test” value=”test” />
  <input type=”submit” name=”my_submit” value=”送信” id=”btnSubmit”
   class=”recaptcha” disabled />
</form>

</body>
</html>

サーバー側

<?php
クライアント側からのreCAPTCHAパラメータ(SiteKey)を取得
$recaptcha = htmlspecialchars($_POST[‘g-recaptcha-response’], ENT_QUOTES, ‘UTF-8’);

if(isset($recaptcha)){
 $captcha = $recaptcha;
}else{
 $captcha = “”;
 echo “captchaエラー”;
 exit;
}
キー取得で取得したSecretKeyを設定
$secretKey = “XXXXXXXXXXXXXXXXXXXX“;

SiteKeyとSecretKeyを照合
$resp = @file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$captcha}”);
$resp_result = json_decode($resp, true);

if(intval($resp_result[‘success’]) !== 1) {
 echo(‘NG’);
}else{
 echo(‘OK’);
}

セールス

次の記事

営業の魔法