LoginSignup
24
20

More than 5 years have passed since last update.

GoogleのreCAPTCHAをPHPで使う

Posted at

目的

Googleが提供している新しいreCAPTCHAAPIを使ってみる。
https://www.google.com/recaptcha/intro/index.html

Site key/SecretKey発行

管理画面にアクセスしてSite key/SecretKeyを発行する
https://www.google.com/recaptcha/admin
Label:なんでも良さげ
Domains:使用するサイトのドメイン。1行1ドメイン。

クライアントサイド

javascriptを読み込み
<script src='https://www.google.com/recaptcha/api.js'></script>

HTML記述
<div class="g-recaptcha" data-sitekey="{{SITEKEY}}"></div>

サーバサイド

GoogleAPIに対してリクエストを発行します。

recaptcha.php
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
    'secret' => '{{SECRETKEY}}',
    'response' => $_REQUEST['g-recaptcha-response'],
    'remoteip' => $_SERVER['REMOTE_ADDR'],
);
$url .= '?' . http_build_query($data);
$header = Array(
    'Content-Type: application/x-www-form-urlencoded',
);
$options = array('http' =>
    array(
        'method' => 'GET',
        'header'  => implode("\r\n", $header),
        'ignore_errors' => true
    )
);
$apiResponse = file_get_contents($url, false, stream_context_create($options));
$jsonData = json_decode($apiResponse, TRUE);
if($jsonData['success'] !== TRUE){
    echo '失敗した';
}

まとめ

簡単にCAPTCHAが実装できます。
さらに、正規ユーザが読めない文字を解読する必要がないのでいいと思います。

24
20
1

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
24
20