如果reCaptcha成功,如何提交表格

时间:2019-03-20 02:06:31

标签: javascript php recaptcha

问候所有

我不确定这是否是正确的方法。假设这里有一个表格,并且如果我的验证码返回成功,我该如何将动作发送到login.php?否则,如果返回false则显示错误消息。

我的表格

<div class="login-wrapper">
  <form id="login-form" class="login-form" method="POST" action="login.php">

    <input type="text" id="username" name="username" autofocus/>
    <input type="password" id="password" name="password" />
    <div class="g-recaptcha" data-sitekey="my_site_key"></div>
    <button id="login-button" name="login-submit">login</button>

  </form>   
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</div>

php reCaptcha

<?php
    if(isset($_POST['login-submit'])){
        $username = $_POST['username'];
        $secretKey = "my_secret_key";
        $responseKey = $_POST['g-recaptcha-response'];
        $userIP = $_SERVER['REMOTE_ADDR']; //optional

        $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 "Success";
      // if success form submit to login.php
        else
            // echo "Failed";
      // return error message
    }
?>

2 个答案:

答案 0 :(得分:0)

另一种方法是使用reCaptcha的JS版本,然后在reCaptcha成功时添加此脚本以提交表单

document.getElementById("login-form").submit();

寻找JS API https://developers.google.com/recaptcha/docs/display

答案 1 :(得分:0)

我认为您在这里没有什么逻辑问题,您已经在做正确的事情,您只需要在验证码检查脚本中添加您的登录功能,反之亦然。 这意味着您可以直接将表单提交给login.php,并在那里检查recatcha是否正确,如果是,则继续登录功能,如果没有,则返回错误。 您只需要对现有代码进行少量更改。

HTML

<div class="login-wrapper">
  <form id="login-form" class="login-form" method="POST" action="login.php">    
    <input type="text" id="username" name="username" autofocus/>
    <input type="password" id="password" name="password" />
    <div class="g-recaptcha" data-sitekey="my_site_key"></div>
    <button id="login-button" name="login-submit">login</button>    
  </form>   
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</div>

LOGIN.php

<?php
    if(isset($_POST['login-submit'])){
        $username = $_POST['username'];
        $password = $_POST['password ']; //password for login check
        //check recaptcha
        $secretKey = "my_secret_key";
        $responseKey = $_POST['g-recaptcha-response'];
        $userIP = $_SERVER['REMOTE_ADDR']; //optional    
        $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 "Success";
            // IF SUCCESS PROCEED WITH YOUR LOGIN CHECKING FUCTIONS HERE
        }else{
            // echo "Failed";
            // RETURN ERROR MESSAGE
        }
    }
?>