我正在努力以多页形式整合 recaptcha

I'm struggling with integrating recaptcha in multipage form

背景资料: 我制作了一个包含多个页面的测试表单。当 recaptcha 没有集成时,我会在我的数据库中收到信息。但是,当尝试集成 recaptcha(checkbox v2)时,它一直失败,并且信息不再发送到数据库。我试图在 page2.php 上集成 recaptcha,因为它是用户必须填写的表单的最后一页。我留下了我的 recaptcha 密钥,因为它只是作为测试制作的。

问题: 我怎样才能让它发挥作用?如何以正确的方式整合 recaptch? 谢谢!

包含的页面是:

footer.php

    <!-- Bootstrap Javascript-->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
 <script>function goBack() {window.history.back();}</script>

 <!-- recaptcha -->
 <script src='https://www.google.com/recaptcha/api.js'></script>

  </body>
</html>

header.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('config.php');
require_once('functions.php');
session_start();
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Multi-Page Form</title>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">

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

  </head>
  <body>
    <nav class="navbar navbar-inverse">
      <div class="container">
      </div>
    </nav>

index.php

<?php include_once('header.php'); ?>



  <section id="form">
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <div class="form-container">
            <h3 class="heading">Questionnaire</h3>
            <p> Beste user,</p>
            <p> Please fill in form A or B</p>
            <br>
            <p><a href="page1.php">Form A</a></p>
            <br>
            <p><a href="">Form B</a></p>
        </div>
        </div>
      </div>
    </div>
  <section>
<?php include_once('footer.php'); ?>

page1.php

<?php include_once('header.php');?>
  <section id="form">
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <div class="form-container">
            <h3 class="heading">Step 1/2</h3>

            <form action="page2.php" method="post">
                  <?php
                        echo "<br>";
                      email('Email', 'Email', '<b>Email</b>', ' ');
                        echo "<br>";
                      text('Firstname', 'Firstname', '<b>Firstname</b>', ' ');
                        echo "<br>";
                    ?>
                <br>
                <br>  
                <center>
                     <div class="btn-group">

                        <button class="btn btn-dark" onclick="goBack()">&laquo;  Go back</button>
                        <button class="btn btn-dark" type="reset" value="reset">Reset</button>
                        <button class="btn btn-dark" type="submit">Continue &raquo;</button>

                    </div>   
                </center>   
            </form>

        </div>
        </div>
      </div>
    </div>
  <section>
<?php include_once('footer.php'); ?>

page2.php

<?php
include_once('header.php');

// Store data from page 1 in SESSION
if ( ! empty( $_POST ) ) {
  $_SESSION['Email'] = $_POST['Email'];
  $_SESSION['Firstname'] = $_POST['Firstname'];
  }

// recaptcha
$public_key = "6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S"; 
$private_key = "6LdojMIUAAAAALhEfrQFR3jExbPLubKjys6CZL_9";
$url = "https://www.google.com/recaptcha/api/siteverify"; 

?>
  <section id="form">
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <div class="form-container">
            <h3 class="heading">Step 2/2</h3>
            <form action="page3.php" method="post">

              <?php

                    // choices for checkbox
                        $options = array(
                        'No ' => 'No ',
                        'Neutral ' => 'Neutral ',
                        'Yes ' => 'Yes ',
                        );

                    // choices for checkbox2
                        $options2 = array(
                        'Internet ' => 'Internet ',
                        'Friends ' => 'Friends ',
                        'Work ' => 'Work ',
                        'Other' => 'Other' ,
                        );

                    echo "<br>";
                  checkbox2( 'Info_media', 'Info_media', '<b>How do you know this?</b>', $options2 );
                    echo "<br>"; 
                  text_non_required('Other', 'Other', 'Explain "Other"?', ' ');
                    echo "<br>";
                  checkbox( 'Question_1', 'Question_1', '<b>Do you agree with the answer?</b>', $options );
                    echo "<br>";
                  text('Remark', 'Remark', 'Do you have remarks?', ' ');
            ?>

                <br>
                <br>  
                <center>

                      <!-- recaptcha -->
                      <div class="g-recaptcha" data-sitekey="<?php print $public_key; ?>"></div>
                      <br>

                      <div class="btn-group">
                      <button class="btn btn-dark" onclick="goBack()">&laquo; Go back</button>
                      <button class="btn btn-dark" type="reset" value="reset">Reset</button>
                      <button class="btn btn-dark" name="submit_form" type="submit">Continue &raquo;</button>

                      <!-- recaptcha -->
                      <?php
                        /* Check if the form has been submitted */
                            if(array_key_exists('submit_form',$_POST))
                            {
                                $response_key = $_POST['g-recaptcha-response'];
                                $response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
                                /* json decode the response to an object */
                                $response = json_decode($response);

                                /* if success */
                                if($response->success == 1)
                                {
                                    header("Location: http://localhost/recaptcha_test/page3.php");
                                }
                                else
                                {
                                    echo "You are a robot.";
                                }
                            }
                          ?>

                    </div>   
                </center>         

            </form>
          </div>
        </div>
      </div>
    </div>
  <section>
<?php include_once('footer.php'); ?>

page3.php

<?php
include_once('header.php');

// Store data in session
if ( ! empty( $_POST ) ) {
  $_SESSION['Info_media'] = $_POST['Info_media'];
  $_SESSION['Other'] = $_POST['Other'];
  $_SESSION['Question_1'] = $_POST['Question_1'];
  $_SESSION['Remark'] = $_POST['Remark'];
    }

?>
  <section id="form">
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <div class="form-container">
            <h3 class="heading">You are done.</h3>
            <br>
            <br>
              <center>Thank you.</center>
              <br>

               <?php              
                whitelist_convert_send ();
              ?>


            </div>
        </div>
      </div>
    </div>
  <section>
<?php include_once('footer.php'); ?>

functions.php

<?php
function __($text) {
  return htmlspecialchars($text, ENT_COMPAT);
}

function checked($value, $array) {
  if ( in_array( $value, $array ) ) {
    echo 'checked="checked"';
  }
}

function text( $name, $id, $label, $placeholder, $type = 'text' ) {?>
  <div class="form-group">
    <label for="<?php echo $id; ?>"><?php echo $label; ?></label>
    <input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control" 
           id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
           value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
  </div>
<?php }

function text_non_required( $name, $id, $label, $placeholder, $type = 'text' ) {?>
  <div class="form-group">
    <label for="<?php echo $id; ?>"><?php echo $label; ?></label>
    <input type="<?php echo $type; ?>" name="<?php echo $name; ?>" class="form-control" 
           id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
           value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
  </div>
<?php }

function email( $name, $id, $label, $placeholder, $type = 'email' ) {?>
  <div class="form-group">
    <label for="<?php echo $id; ?>"><?php echo $label; ?></label>
    <input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control" 
           id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
           value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
  </div>
<?php }

function checkbox( $name, $id, $label, $options = array() ) {?>
  <div class="form-group">
    <p><?php echo $label; ?></p>
    <?php foreach ($options as $value => $title ) : ?>
      <label class="checkbox-inline" for="<?php echo $id; ?>">
        <input type="radio" required name="<?php echo $name; ?>[]" value="<?php echo $value; ?>" <?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>>
        <span class="checkbox-title"><?php echo $title; ?></span>
       </label>
    <?php endforeach; ?>
  </div>
<?php }

function checkbox2 ($name, $id, $label, $options2 = array() ) {?>
    <div class="form-group">
        <p><?php echo $label; ?></p>
            <?php foreach ($options2 as $value => $title) :
            ?>
            <label class="checkbox-inline" for="<?php echo $id; ?>">
               <input type="radio" required name="<?php echo $name; ?>[]" 
                           value="<?php echo $value; ?>"
                           <?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>
                >
                <span class="checkbox-title"><?php echo $title; ?></span>
            </label>
            <?php endforeach; ?>
    </div>
<?php 

}

function whitelist_convert_send () {

    //globalise variables
        global $Email;
        global $Firstname;
        global $Info_media;
        global $Other;
        global $Question_1;
        global $Remark;
        global $MCQ_0;
        global $MCQ_1;


    // Whitelist
        $Email = $_SESSION['Email'];
        $Firstname = $_SESSION['Firstname'];
        $Info_media = $_SESSION['Info_media'];
        $Other = $_SESSION['Other'];
        $Question_1 = $_SESSION['Question_1'];
        $Remark = $_SESSION['Remark'];

    // arrays to value in string for performing statistics
        foreach ($Info_media as $value) {
        $MCQ_0 = $value;}

        foreach ($Question_1 as $value) {             
        $MCQ_1 = $value;}


    // Connectie database (naam server, gebruikersnaam, wachtwoord, naam database)
                    $conn = new mysqli('localhost', 'root', '', 'Wolf');

                    /*Testing databaseconnection
                    if ($conn){ 
                        echo "we are connected";} 
                    else {
                        die ('database connection failed');} */

                 if (!$conn){ die ('database connection failed' . msqli_error ());} 


                    $stmt = $conn->prepare("INSERT INTO test_database (Email, Firstname, Info_media, Other, Question_1, Remark) VALUES (?, ?, ?, ?, ?, ?)");

                    $stmt->bind_param("ssssss", $Email, $Firstname, $MCQ_0, $Other, $MCQ_1, $Remark);

                // Execute
                  $insert = $stmt->execute();

                // Einde sessie
                    session_destroy();
}

您可能误解了 recaptcha 的工作原理。

  1. 您在表单中集成了验证码 (js + div)
  2. 在结果页面上检查验证码检查是否成功 (php)

目前您正在 page2.php 中进行这两项操作。当此页面加载时,它会检查 recaptcha 是否成功,但 recaptcha 甚至没有包含在内,用户还没有机会解决它:-)

所以你应该在page1集成,在page2查看。

page1.php

在您的表单中集成验证码div

 <form action="page2.php" method="post">
     <div class="g-recaptcha" data-sitekey="6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S"></div>
     <?php
         echo "<br>";
         email('Email', 'Email', '<b>Email</b>', ' ');
         ...

ofc 您也可以将站点密钥与 php 集成(就像您在 page2.php 上所做的那样)或更改表单中的位置

page2.php

从此页面删除验证码 div。 recaptcha 成功检查应该位于此页面开头的某个位置。你应该只在 $response->success == 1 成功时渲染整个表单(见附件代码)。这可能需要对 page2.php

进行一些额外的重组
<?php
    //recaptcha check
    $response_key = "";
    
    //get submitted recaptcha "user response" from last page
    if(array_key_exists('g-recaptcha-response',$_POST)){
        $response_key = $_POST['g-recaptcha-response'];
    }
    $response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
    /* json decode the response to an object */
    $response = json_decode($response);

    if($response->success == 1){
        //render form from page 2
        ?>
        <form action="page3.php" method="post">
            ...
          

       <?php
    }
    else{
        echo "You are a robot.";
        // 
    }
?>

作为替代方案,您可以在 page2.php 中集成 recaptcha 并在 page3.php 中检查结果 - 这仅取决于您希望在哪个步骤中使用 recaptcha 复选框