新的谷歌recaptcha与复选框服务器端PHP

Moa*_*tez 69 php recaptcha

我只是用复选框设置了新的google recaptcha,它在网站端工作正常,但是我不知道如何在服务器端使用php进行操作,我尝试使用下面的旧代码,但即使是不使用recaptcha.

require_once('recaptchalib.php');
$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,
        $_SERVER["REMOTE_ADDR"],
        $_POST["recaptcha_challenge_field"],
        $_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
 $errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';}
Run Code Online (Sandbox Code Playgroud)

Lev*_*ite 108

私钥安全

虽然这里的答案肯定是有效的,但他们正在使用一个GET请求,它会泄露您的私钥(即使https已使用).在Google Developers上指定的方法是POST.

通过POST验证

function isValid() 
{
    try {

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => '[YOUR SECRET KEY]',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];

        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];

        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

数组语法:我使用"new"数组语法([]不是array(..)).如果您的php版本还不支持,那么您必须相应地编辑这3个数组定义(请参阅注释).

返回值:true如果用户有效,false则返回此函数,如果没有,null则返回错误.您可以使用它,例如只需写作if (isValid()) { ... }

  • https网址实际上是加密的,因此即使使用GET请求也不会公开私钥,请参阅:http://stackoverflow.com/questions/499591/are-https-urls-encrypted (5认同)
  • 如果你需要*旧数组语法*,将`$ data = ...`和`$ options = ...`声明更改为:`$ data = array('secret'=>'[你的秘密密钥] ','response'=> $ _POST ['g-recaptcha-response'],'remoteip'=> $ _SERVER ['REMOTE_ADDR']); $ options = array('http'=> array('header'=>"Content-type:application/x-www-form-urlencoded\r \n",'method'=>'POST','content'= > http_build_query($ data)));` (2认同)
  • 您可以将请求保存到服务器并提前保释:```if(empty($ _ POST ['g-recaptcha-response'])){return false; }``` (2认同)

小智 101

这是解决方案

的index.html

<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>
Run Code Online (Sandbox Code Playgroud)

verify.php

<?php
    $email; $comment; $captcha;

    if(isset($_POST['email']))
        $email=$_POST['email'];
    if(isset($_POST['comment']))
        $comment=$_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 = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($response['success'] == false)
    {
        echo '<h2>You are spammer ! Get the @$%K out</h2>';
    }
    else
    {
        echo '<h2>Thanks for posting comment.</h2>';
    }
?>
Run Code Online (Sandbox Code Playgroud)

http://codeforgeek.com/2014/12/google-recaptcha-tutorial/

  • reCAPTCHA表单字段值将直接连接到验证URL.攻击者可以使用它在验证请求上注入任意形式的参数,可能会绕过CAPTCHA.要解决这个问题,请像下面这样清理验证码变量:`urlencode($ captcha)` (14认同)
  • 数据应按照[在文档]中指定的方式发布(https://developers.google.com/recaptcha/docs/verify#api-request).此代码使用GET方法.我会对[Levit的答案](http://stackoverflow.com/a/30749288/412004)进行修改. (6认同)
  • 此代码不会对攻击者可用于破坏代码的参数进行编码. (2认同)
  • 对我来说效果很好。除了(在index.html中)表单行:`action =“form.php”`,它应该是`action =“verify.php”`。 (2认同)

小智 19

我不喜欢这些解决方案.我改用它:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'secret' => $privatekey,
    'response' => $_POST['g-recaptcha-response'],
    'remoteip' => $_SERVER['REMOTE_ADDR']
]);

$resp = json_decode(curl_exec($ch));
curl_close($ch);

if ($resp->success) {
    // Success
} else {
    // failure
}
Run Code Online (Sandbox Code Playgroud)

我认为这是优越的,因为你确保它被发布到服务器并且它没有进行尴尬的'file_get_contents'调用.这与此处描述的recaptcha 2.0兼容:https://developers.google.com/recaptcha/docs/verify

我觉得这个更清洁了.我看到大多数解决方案都是file_get_contents,当我觉得卷曲就足够了.

  • 如果由于在php.ini中禁用了“ allow_url_fopen”而无法使用file_get_contents(),这是一个很好的工作解决方案。为我工作。+1。 (2认同)

小智 7

简单而最佳的解决方案如下.
的index.html

<form action="submit.php" method="POST">
   <input type="text" name="name" value="" />
   <input type="text" name="email" value="" />
   <textarea type="text" name="message"></textarea>
   <div class="g-recaptcha" data-sitekey="Insert Your Site Key"></div>
   <input type="submit" name="submit" value="SUBMIT">
</form>
Run Code Online (Sandbox Code Playgroud)

submit.php

<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
  if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
    //your site secret key
    $secret = 'InsertSiteSecretKey';
    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
    $responseData = json_decode($verifyResponse);
    if($responseData->success){
        //contact form submission code goes here

        $succMsg = 'Your contact request have submitted successfully.';
    }else{
        $errMsg = 'Robot verification failed, please try again.';
    }
  }else{
    $errMsg = 'Please click on the reCAPTCHA box.';
  }
}
?>
Run Code Online (Sandbox Code Playgroud)

我从这里找到了这个参考和完整的教程 - 使用新的Google reCAPTCHA和PHP


Yer*_*rke 5

我喜欢 Levit 的回答并最终使用了它。但我只是想指出,以防万一,有一个用于新 reCAPTCHA 的官方 Google PHP 库:https : //github.com/google/recaptcha

最新版本(现在是 1.1.2)支持 Composer 并包含一个示例,您可以运行该示例来查看是否正确配置了所有内容。

下面你可以看到这个官方库附带的部分示例(为了清楚起见,我做了一些小的修改):

// Make the call to verify the response and also pass the user's IP address
    $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

    if ($resp->isSuccess()) {
// If the response is a success, that's it!
        ?>
        <h2>Success!</h2>
        <p>That's it. Everything is working. Go integrate this into your real project.</p>
        <p><a href="/">Try again</a></p>
        <?php
    } else {
// If it's not successful, then one or more error codes will be returned.
        ?>
        <h2>Something went wrong</h2>
        <p>The following error was returned: <?php
            foreach ($resp->getErrorCodes() as $code) {
                echo '<tt>' , $code , '</tt> ';
            }
            ?></p>
        <p>Check the error code reference at <tt><a href="https://developers.google.com/recaptcha/docs/verify#error-code-reference">https://developers.google.com/recaptcha/docs/verify#error-code-reference</a></tt>.
        <p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.</p>
        <p><a href="/">Try again</a></p>
    <?php
    }
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助某人。