![見出し画像](https://assets.st-note.com/production/uploads/images/85891983/rectangle_large_type_2_62e59edb10c4697c6e79e598f191fe44.png?width=1200)
ReCaptchaの設置方法
スパム対策にreCaptchaを設定してみた。
ネットに落ちてるプログラムを使えばかなり簡単。
(1)Googleにサインインしてhttps://www.google.com/recaptcha/admin/createにアクセス
(2)
ラベル:サイト名
reCAPTCHA タイプ:reCAPTCHA v2
ドメイン:サイトのドメイン
を入力し送信
![](https://assets.st-note.com/img/1661949443132-CywCczs7Xg.png?width=1200)
(3)サイトキー、シークレットキーが出てくるのでメモ。
(4)keys.phpを作成し、非公開フォルダに置く。
<?php
return [
'V2_SITEKEY' => 'サイトキー',
'V2_SECRETKEY' =>'シークレットキー',
];
?>
(5)chaptchaの結果を返すfunctionを作る。これをさまざまなファイルから読み込んで使うのだけれど
これはこのサイトの内容を自分が使いやすいよう改良したもの。
https://www.webdesignleaves.com/pr/plugins/google_recaptcha.php
<?php
function chaptcha($responce,$path){
$result_status = '準備中';
$config = include($path);
$siteKey = $config['V2_SITEKEY'];
$secretKey = $config['V2_SECRETKEY'];
//echo 'saitokey:'.$siteKey;
if ( isset($responce) ) {
//echo 'リスポンス'.$_POST[ 'g-recaptcha-response' ];
//cURL セッションを初期化
$ch = curl_init();
// curl_setopt() により転送時のオプションを設定
//API の URL の指定
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
//HTTP POST メソッドを使う
curl_setopt($ch, CURLOPT_POST, true );
//API パラメータの指定
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'secret' => $secretKey,
'response' => $responce
)));
//curl_execの返り値を文字列にする
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//転送を実行してレスポンスを $json に格納
$json = curl_exec($ch);
//セッションを終了
curl_close($ch);
//レスポンスの $json(JSON形式)をデコード
$result = json_decode( $json );
if ( $result->success ) {
$result_status = '成功';
//echo '渡す前'.$result_status;
// 成功した場合の処理(メールの送信など)を実行(または結果を変数に入れて、その変数を使って処理を分岐するなど)
} else {
$result_status = '失敗';
// error-codes は配列(以下は最初のエラーを取得)
$result_status .= $result->{'error-codes'}[ 0 ];
//echo '渡す前'.$result_status;
}
}else{
$result_status = '変数なし';
}
return $result_status;
}
?>
↑chapcha.php
(6)フォームのHTML側にこれを追加
include ('パス/chapcha.php');
$config = include('パス/keys.php');
$siteKey = $config['V2_SITEKEY'];
$secretKey = $config['V2_SECRETKEY'];
<form action="check.php" method="post">
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>"></div>
</form>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
(7)PHP側にはこちらを追加
include ('パス/chapcha.php');
$config = include('パス/keys.php');
$siteKey = $config['V2_SITEKEY'];
$secretKey = $config['V2_SECRETKEY'];
$message =chaptcha($_POST[ 'g-recaptcha-response' ],'パス/keys.php');
if ($message!='成功'){
//chaptchaが失敗したときの処理を書く
$errors['chaptcha'] = "ロボットではありませんにチェックを入れてください。";
}