同一页面中的多个Google Recaptcha

时间:2017-04-01 03:23:24

标签: javascript recaptcha

我在这里有一个问题,我在我的页面上包含2个recaptchas并且它们正常工作,但是在清理它们时(在通过ajax提交之后)我无法重置recaptcha,如果我使用&# 34; grecaptcha.reset"它擦了一个recaptcha .. 谢谢!

1 个答案:

答案 0 :(得分:0)

这是我的简单解决方案,这样你就可以在同一页面上准备尽可能多的验证码。记得放谷歌api元素:SiteKey和SecretKey!

后端:

<?php

$siteKey = 'Paste element provided by google api';
$secretKey = 'Paste element provided by google api';

if($_POST['submit']){

    $username = $_POST['username'];
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response = file_get_contents($url);
    $response = json_decode($response);
    if($response->success){
        echo "Verification is correct. Your name is $username";
    } else {
        echo "Verification failed";
    }
}?>

前端:

<html>
<meta>
    <title>Google ReCaptcha</title>
</meta>
<body>
    <h3>First form</h3>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div id="recaptcha1"></div>
        <input type="submit" name="submit" value="send"/>
    </form>


    <h3>Second form</h3>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div id="recaptcha2"></div>
        <input type="submit" name="submit" value="send"/>
    </form>


    <script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
    <script>
        var recaptcha1;
        var recaptcha2;
        var myCallBack = function() {

            recaptcha1 = grecaptcha.render('recaptcha1', {
                'sitekey' : '<?= $siteKey ?>',
                'theme' : 'light'
            });

            recaptcha2 = grecaptcha.render('recaptcha2', {
                'sitekey' : '<?= $siteKey ?>',
                'theme' : 'dark'
            });
        };
    </script>
</body>

干杯!