web-dev-qa-db-ja.com

recaptcha v2とフォーム送信に苦労しています

https://developers.google.com/recaptcha/docs/verify

if(isset($_POST['submit'])){
$recaptchaResponse = $_POST['g-recaptcha-response'];
$secretKey = 'MYKEY';
$request = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$recaptchaResponse);

    if(!strstr($request,"false")){
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You didnt complete the captcha.</p></div>';
exit();

その後、残りのphpファイルはフォームをメールで送信しますが、recaptchaを完了しなくても送信するだけです。基本的に、JSONがfalseを返す場合、送信しないでエラーを表示することを望んでいました

また、ここに役立つ場合は、ページのフォームもあります。私もおそらく何か間違ったことをしました...

<form method="POST" action="post.php" name="contactform" id="contactform" class="container">

            <fieldset>
                <div class="form-field grid-half">
                    <label for="name">Name</label>
                    <span><input type="text" name="name" id="name" /></span>
                </div>
                <div class="form-field grid-half">
                    <label for="email">Email</label>
                    <span><input type="email" name="email" id="email" /></span>
                </div>
                <div class="form-field grid-full">
                    <label for="message">Message</label>
                    <span><textarea name="message" id="message"></textarea></span>
                </div>                  
                <div class="form-field grid-full">
                        <div class="g-recaptcha" data-sitekey="MYKEY"></div>
                </div>
            </fieldset>
            <div class="form-click grid-full">
                <span><input type="submit" name="submit" value="Submit" id="submit" /></span>
            </div>

            <div id="alert" class="grid-full"></div>
        </form>     
14
millsteedo

PHP version/config)によっては、オブジェクトへの直接アクセスが機能しない場合があるため、json_decode()を使用します。

/* $response object returned from https://www.google.com/recaptcha/api/siteverify via which ever method you use */

$obj = json_decode($response);
if($obj->success == true)
{
    //passes test
}
else
{
    //error handling
}
24
Alan Kael Ball

file_get_contentsの代わりにcurlを使用します(私のように、サーバー設定でfile_get_contentsを無効にしたい場合)

$post_data = "secret=__your_secret_key__&response=".
   $_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR'] ;

$ch = curl_init();  
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, 
   array('Content-Type: application/x-www-form-urlencoded; charset=utf-8', 
   'Content-Length: ' . strlen($post_data)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); 
$googresp = curl_exec($ch);       
$decgoogresp = json_decode($googresp);
curl_close($ch);

if ($decgoogresp->success == true)
    {
    // Success
    }
20
Peter

HTMLテンプレートの終了タグの前にこのスニペットを貼り付けます。

<script src='https://www.google.com/recaptcha/api.js'></script>

ReCAPTCHAウィジェットを表示する場所の最後にこのスニペットを貼り付けます。

<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>

例:

<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
       <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
    </form>
  </body>
</html>

form.php

<?php

        $email;$comment;$captcha;
        if(isset($_POST['email'])){
          $email=$_POST['email'];
        }if(isset($_POST['comment'])){
          $email=$_POST['comment'];
        }if(isset($_POST['g-recaptcha-response'])){
          $captcha=$_POST['g-recaptcha-response'];
        }
        if(!$captcha){
          echo '<h2>Please check the the captcha form.</h2>';
          exit;
        }
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR_SECRET_KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
        if($response.success==true)            
        {
          echo '<h2>Thanks for posting comment.</h2>';
        }
?>

ソース:

6
Elshan

まず、ここで既に与えられた答えは絶対に適切です。そうは言っても、これらの答えをもう少し便利なメソッドにラップするこの関数を含めたかっただけです。そうすれば、関数ライブラリにそれらを投げ込み、Googleが何かを変更するまでそれをほとんど忘れることができます。楽しい!

//Put these two functions into your function library-------
function CaptchaVerify($apiSecret)
{
    //Returns -1 if no captcha response was in post(user did not submit form)
    //Returns 0 if the verification fails
    //Returns 1 if the verification succeeds
    $captcha = isset($_POST['g-recaptcha-response'])? "&response=".$_POST['g-recaptcha-response']:'';
    if($captcha != '')
    {
        $verifyUrl = "https://www.google.com/recaptcha/api/siteverify";
        $apiSecret = "?secret=".$apiSecret;
        $remoteip = "&remoteip=".$_SERVER['REMOTE_ADDR'];
        $response=file_get_contents($verifyUrl.$apiSecret.$captcha.$remoteip);
        $obj = json_decode($response);
        return (integer)$obj->success;          
    }
    return -1;
}
function MyCaptchaVerify()
{
    $apiSecret = "PUT YOUR CAPTCHA SECRET HERE";
    return CaptchaVerify($apiSecret);
}
//-------------------------------------------------------
//Example usage in your form
switch(MyCaptchaVerify())
{
    case -1:echo "The form has not been submitted yet(First Load).<br>";break;
    case  0:echo "The captcha verification failed.<br>";    break;
    case  1:echo "The captcha verification succeeded.<br>"; break;
}
5
Paul Ishak

File_get_contentsよりもcURLの例を好むのは、エラーログなどのオプションが増えるからです。ただし、cURLが非常に気難しいと感じる人もいます。これらのユーザーにとって、Guzzleは非常に優れた代替手段です。

1
Surya

応答を取得するためにCurl PHPを使用する場合は、次のコードを使用できます。

  if(isset($_POST['submit'])){
     $privatekey = "paste_your_privatekey";
     $responseKey = $_POST["g-recaptcha-response"];
     $userIP = $_SERVER["REMOTE_ADDR"];

     /////Curl Start///////
     $ch = curl_init();

     curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, "secret=$privatekey&response=$responseKey&remoteip=$userIP");

     // Receive server response ...
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

     $server_output = curl_exec($ch);
     $response = json_decode($server_output);

     curl_close ($ch);
     /////Curl Close///////

     // Further processing ...
     if ($response->success == "true") {
        Success……..
     }esle{
        Failed…………….
     }
  }
0
Ariful Haque