Kristof
Kristof

Reputation: 33

I'm struggling with integrating recaptcha in multipage form

Background info: I have made a test form containing multiple pages. When recaptcha isn't intergrated I receive the info in my database. But when trying to integrate recaptcha (checkbox v2) it keeps failing and the info isn't sent to the database no more. I have tried to intergrate recaptcha on page2.php because it's the last page of the form the user has to fill in. I left my recaptcha keys in because it's just made as test.

Question: How can I make it work? How can I integrate recaptch in a correct way? Thanks!

The included pages are:

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();
}

Upvotes: 2

Views: 605

Answers (1)

Evil_skunk
Evil_skunk

Reputation: 3392

You probably misunderstood how recaptcha is working.

  1. You integrate the recaptcha code (js + div) in your form
  2. On the result page you check if the captcha check was sucessful (php)

Currently you are doing both things in page2.php. When this page is loading, it checks if recaptcha was successful, but the recaptcha was not even included and the user didn't had the opportunity to solve it yet :-)

So you should integrate it in page1 and check it in page2.

page1.php

Integrate the recaptcha div in your form

 <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 you can integrate the site key with php too (like you have done it on page2.php) or change the position inside the form

page2.php

Remove the recaptcha div from this page. The recaptcha success check should be somewhere in the beginning of this page. You should render the whole form only when $response->success == 1 succeed (see the attached code). This probably requires some additional restructuring of 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.";
        // 
    }
?>

As an alternative you could integrate recaptcha in page2.php and check the result in page3.php - it just depends in which step you want the recaptcha checkbox

Upvotes: 1

Related Questions