Oct 20, 2017

How to use reCAPTCHA V2 in PHP

How to use reCAPTCHA V2 in PHP
(PHP プログラムでの reCAPTCHA V2 の利用法)

I got the mail from Google. It said "reCAPTCHA V1" will be turned off on March 31, 2018.
(Google から、reCAPTCHA V1 が 2018-03-31に終了するので V2へ移行して欲しいと連絡メールが届いた)

This is my implment of reCAPTCHA V2.
(以下は、reCAPTCHA V2の私の実装です)

xxxx.php // sample PHP code for  reCAPTCHA V2

//See https://developers.google.com/recaptcha/docs/verify
//See https://www.google.com/recaptcha/admin#site/999999999
//Key Settings : Label: www.mydomain.com, Domains: www.mydomain.com, Owners: myname@gmail.com
$publickey = "9AAAAAAAAAAAAAAA_AAAAAA"; // you got this from the signup page
$privatekey = "9BBBBBBBBBBBBBBBB-BBBBBBBBBBBBBB";

if(isset($_POST['g-recaptcha-response'])){
  $url = "https://www.google.com/recaptcha/api/siteverify";
  $data = array('secret' => $privatekey, 
     'response' => $_POST['g-recaptcha-response'], 
     'remoteip' => $_SERVER["REMOTE_ADDR"]);
  $content = http_build_query($data);
  $content_length = strlen($content);
  $options = array('http' => array(
    'method' => 'POST',
    'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
."Content-Length: $content_length",
    'content' => $content));
  //Send https-post to the recaptcha server
  $response = file_get_contents($url, false, stream_context_create($options));
  $answers = json_decode($response);
  if($answers->{'success'}){
// OK recaptcha, 
        header("Location: http://www.mydomain.com/nextpage.php");
  }else{
        // ERROR recaptcha
$err_mess = T_ERROR_CAPTCHA_TEST
           ."(reCAPTCHA said: " . $answers->{'error-codes'} . ")";
        header("Location: http://www.mydomain.com/error.php?err_mess=".urlencode($err_mess);
  }
}
......
echo "<head>\n";
...........
echo "<script src='https://www.google.com/recaptcha/api.js'></script>\n";
echo "</head>\n";
echo "<body>\n";
...........
echo "<form method=\"POST\" action=\"xxxx.php\">\n";
echo "<div class=\"g-recaptcha\" data-sitekey=\"".$publickey."\"></div>\n";
echo "<input type=submit name=check_CAPTCHA_stage value=\"".T_SUBMIT."\">\n";
echo "</form>\n";
...........
echo "</body>\n";
............

No comments:

Post a Comment