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

How to submit a form if reCaptcha success

大家好,

我不确定这是不是正确的方法。假设这里有一个表格,如果我的 recaptcha return 成功,我如何将操作发送到 login.php? else if return 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 验证码

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

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

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

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

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

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