Jump to content

Adding Google recaptcha 3 to working PHP form


sn0wman23

Recommended Posts

I am a php newbie and with help from someone on this forum managed to get my php form working. I am now trying to add recaptcha 3 but can't get it to work. I have added my code to this post and would appreciate some pointers. 


<?php
/* This is the Header PHP file */
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="My Name">

    
    <title>My Title</title>

    <!--Bootstrap Core CSS-->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">

    <!--Font Awresome Icons-->
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600&display=swap" rel="stylesheet">

    <!--Google Fonts-->
    <link href="assets/css/fontawesome/css/all.min.css" rel="stylesheet">

    <!--Adobe Typekit Fonts-->
    <link href="https://use.typekit.net/jtf1geg.css" rel="stylesheet">

    <!--Custom CSS-->
    <link href="assets/css/custom.css" rel="stylesheet">

    <!--Favicon-->
    <link rel="icon" type="image/png" sizes="32x32" href="assets/img/MyFavicon32WhiteAlt.png">

    <!--Google reCaptcha-->  
    <script src="https://www.google.com/recaptcha/api.js"></script>
    <script>
      function onSubmit(token) {
        document.getElementById("contact-form").submit();
      }
    </script>


  </head>

  <body>
    <!--HEADER-->
    <header class="site-header">
      <!--Navbar-->
      <nav class="navbar">
        <!-- Navbar brand -->
        <div class="navbar-brand">
          <img src="assets/img/myLogo.png" id="wd-logo" alt="My Logo">
        </div>
        
        <!-- Linking Menu Text to Collapse Button -->
        <div class="menu-button">
          <button class="navbar-toggler button" type="button" data-toggle="collapse" data-target="#navbarSupportedContent20"
          aria-controls="navbarSupportedContent20" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-text">Menu</span>
          </button>
          
          <!-- Collapse Button -->
          <button class="navbar-toggler button animated-icon" type="button" data-toggle="collapse" data-target="#navbarSupportedContent20"
            aria-controls="navbarSupportedContent20" aria-expanded="false" aria-label="Toggle navigation">
              <span></span>
              <span></span>
              <span></span>
          </button>
          <!-- Collapse Button End -->
        </div>
        <!-- Linking Menu Text to Collapse Button End -->

        <!-- Collapsible content -->
        <div class="collapse navbar-collapse" id="navbarSupportedContent20">
          <!-- Links -->
          <ul class="navbar-nav">
            <li class="nav-item">
              <a class="nav-link" href="index.php">Home</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="contact.php">About</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="contact.php">Services</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="contact.php">Our Work</a>
            </li>
            <li class="nav-item active">
              <a class="nav-link" href="contact.php">Contact<span class="sr-only">(current)</span></a>
            </li>
          </ul>
          <!-- Links End -->
        </div>
        <!-- Collapsible Content End -->
      </nav>
      <!--Navbar End-->

    </header>
    <!--Header End-->

    <hr>

    <!--Content-->
    <section class="main">
 


<?php
  // This is the contact form
  // Message Vars
  $msg = '';
  $msgClass = '';

  // Check to see if the form has been submitted
  if(filter_has_var(INPUT_POST, 'submit')) {
    // Input Data Variables
    $firstname = htmlspecialchars($_POST['firstname']);
    $lastname = htmlspecialchars($_POST['lastname']);
    $phonenumber = htmlspecialchars($_POST['phonenumber']);
    $email = htmlspecialchars($_POST['email']);
    $dropdown = htmlspecialchars($_POST['selectdropdown']);
    $message = htmlspecialchars($_POST['message']);
    $checkbox = htmlspecialchars($_POST['checkbox'] ?? 0);


    // Check required fields
    if(!empty($firstname) && !empty($lastname) && !empty($phonenumber) && !empty($email) && !empty($dropdown) && !empty($message) && !empty($checkbox)) {
      // If passed, check email address

      if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) { 
        // If failed, Email address is not valid
        $msg = 'Please use a valid email address';
        $msgClass = 'alert-danger';
      } else {

        // Recipient email address and information to be sent to them
        $toEmail = 'hello@example.co.uk';
        $subject = 'Contact Request from  Website';
        $body = '<h2>Contact Request</h2>
                <h4>Name</h4><p>'.$firstname.  ' '.$lastname.'</p>
                <h4>Phone Number</h4><p>'.$phonenumber.'</p>
                <h4>Email Address</h4><p>'.$email.'</p>
                <h4>Subject</h4><p>'.$dropdown.'</p>
                <h4>Message</h4><p>'.$message.'</p>';

        // Email Headers
        $headers = "MIME-VERSION: 1.0" ."\r\n";
        $headers .="Content-Type:text/html;charset=UTF-8" ."\r\n";

        // Additional Headers
        $headers .= "From: " .$firstname. "".$lastname." <".$email.">" ."\r\n"; 

        $recaptcha_url = "https://www.google.com/recaptcha/api/siteverify";
        $recaptcha_secret ="secrettoken";
        $recaptcha_response = $_POST['g-recaptcha-response'];

        $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
        $recaptcha = json_decode($recaptcha, true);

        if($recaptcha['success'] == 1 AND $recaptcha['score'] >= 0.5 AND $recaptcha['action'] == "submit") {
          
          if(mail($toEmail, $subject, $body, $headers)) {
            // Message Sent
            $msg = 'Verfication successful, your message has been sent';
            $msgClass = 'alert-success';
          } else {
            // Message failed
            $msg = 'Your message has NOT been sent';
            $msgClass = 'alert-danger';
          }
        }
      }  
    } else {
      // Failed
      $msg = 'Please fill in all fields';
      $msgClass = 'alert-danger';
    }
  }

?>

      <div class="container clearfix content-container">
        <h1 class="section-title">Contact Us</h1>
        <p>If you have any questions about the services we provide or would like to chat about a new website project, please get in touch using any of the options below. We would love to hear from you!</p>

        <!--Contact Page Row-->
        <div class="row">
          <div class="col-lg-6 contact-details">
            <div class="row">
              <div class="col-lg-12">
                <img src="assets/img/contact-us.jpg" class="img-responsive d-block contact-image" alt="Contact Us Image">
              </div>
            </div>
            <div class="row">
              <div class="col-lg-12 contact-name">
                <span class="d-inline-block contact-inline-block"><i class="fas fa-user fa-2x">
                </i></span>
                <span class="d-inline-block"><p class="contact-details">me</p></span>   
              </div>
            </div>
            <div class="row">
              <div class="col-lg-12 contact-phone">
                <span class="d-inline-block contact-inline-block"><a href="tel:01234 567890"><i class="fas fa-mobile-alt fa-2x"></i></a></span>
                <span class="d-inline-block"><a href="tel:01234 567890"><p class="contact-details">01234 567890</a></p></span>  
              </div>
            </div>
            <div class="row">
              <div class="col-lg-12 contact-email">
                <span class="d-inline-block contact-inline-block"><a href="mailhandler.php"><i class="fas fa-envelope-square fa-2x"></i></a></span>
                <span class="d-inline-block"><a href="mailhandler.php"><p class="contact-details">hello@wexample.co.uk</a></p></span>  
              </div>
            </div>
            <div class="row">
              <div class="col-lg-12 contact-fb">
                <span class="d-inline-block contact-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><i class="fab fa-facebook-square fa-2x"></a></i></span>
                <span class="d-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><p class="contact-details">@example</a></p></span> 
              </div>
            </div>
          </div>

          <!--Contact Form-->
          <div class="col-lg-6 contact-form d-block">
            <?php if($msg != ''): ?>
              <div class="alert <?php echo $msgClass; ?>"><?php echo $msg; ?></div>
            <?php endif;?>
            <form method="post" action="contact.php" role="form" id="contact-form">
              <div class=" row form-group">
                <div class="col-lg-6">
                  <label for="firstnameid">First name<span class="asterisk"> &#42;</span></label>
                  <input type="text" name="firstname" class="form-control mb-3" id="firstnameid">
                </div>
                <div class="col-lg-6">
                  <label for="lastnameid">Last name<span class="asterisk"> &#42;</span></label>
                  <input type="text" name="lastname" class="form-control mb-3" id="lastnameid">
                </div>
              </div>
              <div class="row form-group">
                <div class="col-lg-6">
                  <label for="phonenumber">Phone number<span class="asterisk"> &#42;</span></label>
                  <input type="tel" name="phonenumber" class="form-control mb-3" id="phonenumberid">
                </div>
                <div class="col-lg-6">
                  <label for="emailid">Email address<span class="asterisk"> &#42;</span></label>
                  <input type="email" name="email" class="form-control mb-3" id="emailid">
                </div>
              </div>
              <div class="row form-group">
                <div class="col-lg-12">
                  <label for="subjectid">How can we help<span class="asterisk"> &#42;</span></label>
                  <select class="form-control mb-3" name="selectdropdown" id="subjectid">
                    <option value="">Please choose an option</option>
                    <option value="I would like to discuss a project">I would like to discuss a project</option>
                    <option value="Existing Web 2 Digital client enquiry">Existing client enquiry</option>
                    <option value="General enquiry">General enquiry</option>
                  </select>
                </div>
              </div>
              <div class="row form-group">
                <div class="col-lg-12">
                  <label for="messageid">Tell us a little bit more<span class="asterisk"> &#42;</span></label>
                  <textarea name="message" class="form-control mb-3" id="messageid" rows="6"></textarea>
                </div>
              </div>
              <div class="row form-group">
                <div class="col-lg-12">
                  <p><span class="asterisk"> &#42;</span> indicates required field</p>
                </div>
              </div>
              <div class="row form-group">
                <div class="col-lg-12 form-check">
                  <input type="checkbox" name="checkbox" class="form-check-input" id="formcheckid">
                  <label for="formcheckid" class=form-check-label mb-3>By checking this tickbox you have confirmed that we can collect the information in this form for the purposes outlined in our <a href="privacypolicy.php">privacy policy.</a></label>
                </div>
              </div>
              <div class="row form-group">
                <div class="col-lg-12">
                  <button type="submit" name="submit" class="btn btn-primary mt-4 g-recaptcha" data-sitekey="sitetoken" data-callback='onSubmit' data-action='submit'>Send Message
                  </button>
                </div>
              </div>
            </form>
          </div>
          <!--Contact Form End-->
        </div>
        <!--Contact Page Row End-->
      </div>
      <!--Container end-->

<?php echo file_get_contents('footer.php'); ?>

 

Link to comment
Share on other sites

What errors are you getting? By saying it just doesn't work could mean anything. Any errors you get can make it easier for you to get help.

Turn on error reporting if you have not done so.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

 

Link to comment
Share on other sites

Thanks for the response. Apologies for not expanding my problem statement. 

The form was working as expected before I tried to add captcha 3. When the form was completed a success message was displayed and an Email sent and received. When some or all of the form was not completed a failure message was received on submit. 

With the captcha 3 code, when the form is completed correctly, a tick is placed in the captcha checkbox, on submit nothing happens. No messages are received, the form fields remain populated. 

I have added the code you suggested but I don't see any errors. However, in the console I can see the following:

contact.php:254 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js.map with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
contact.php:252 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.1/umd/popper.min.js.map with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Any suggestions?

Link to comment
Share on other sites

 

 

Cross-Origin Read Blocking (CORB), an algorithm by which dubious cross-origin resource loads may be identified and blocked by web browsers before they reach the web page..It is designed to prevent the browser from delivering certain cross-origin network responses to a web page.

Edited by DanEthical
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.