如何在服务器端验证Google reCAPTCHA v3?私钥安全通过邮寄方式进行验证

2022-08-30 08:30:16

我刚刚用复选框设置了新的谷歌验证码,它在前端工作正常,但是我不知道如何使用PHP在服务器端处理它。我尝试使用下面的旧代码,但即使验证码无效,也会发送表单。

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>';}

答案 1

私钥安全

虽然这里的答案肯定有效,但它们使用的是请求,该请求会公开您的私钥(即使已使用)。在 Google Developers 上,指定的方法是 POSTGEThttps

有关更多详细信息:https://stackoverflow.com/a/323286/1680919

通过邮寄方式进行验证

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;
    }
}

数组语法:我使用“new”数组语法(而不是)。如果您的php版本尚不支持此功能,则必须相应地编辑这3个数组定义(请参阅注释)。[]array(..)

返回值:如果用户有效,如果用户有效,如果用户有效,并且发生错误,则返回此函数。例如,您可以通过编写truefalsenullif (isValid()) { ... }


答案 2

这是解决方案

索引.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>

验证.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>';
    }
?>

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


推荐