如何使Google验证码在表单中成为必需

时间:2018-07-23 07:27:36

标签: php html ajax recaptcha

我正在尝试设置如果用户未检查验证码则无法提交的表单。验证码必须是强制性的,但我无法做到。 他的任何帮助将不胜感激。 我的代码是:

<form action="#" method="post">
                        <input type="email" name="email" placeholder="E-mail" required="">
                        <input type="password" name="password" placeholder="Password" required="">
                                <div align="center" class="g-recaptcha" data-sitekey="6LdtPmUUAAAAAFmYGrd_JI5k_bNzJD9kUNsv4zS0"
                                style="transform:scale(1);-webkit-transform:scale(1);transform-origin:0 0;-webkit-transform-origin:0 0;"></div>

                        <div class="tp">
                            <input type="submit" name="submit" value="Login">
                        </div>
                    </form>

提交后的代码是

if(isset($_POST['submit'])
 { 
    $email = $_POST['email'];
    $secret = "6LdtPmUUAAAAAKf_wtXpvAhHzwbG9bY-xO_-V0a-";
    $ip = $_SERVER['REMOTE_ADDR'];
    $captcha = $_POST['g-recaptcha-response'];
    $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip$ip");
    $response = json_decode($response);
    if($response->success)
        echo "Verification Success. Your name is : $email";
    else
        echo "Verification failed.";


 }

?>

1 个答案:

答案 0 :(得分:0)

如果验证码未经验证,则需要使用JavaScript限制用户提交表单。首先添加onsubmit attr以形成为:

<form action="#" method="post" onsubmit="return check();">

使用JavaScript提交时,您可以将其检查为:

function check() {
    if (grecaptcha.getResponse() == "") {
        alert("Please verify captcha details.");
            return false;
    }
    return true;
}