Jump to content

add Google recaptcha to contact form


lee_sov

Recommended Posts

hi, as the title suggests, im trying to add recaptcha to our existing contact form. Ive got it to display in the form but cant get the 2nd stage verify part to work, i.e. the form is sent whether I tick the box or not! Please see my current code below (emails/passwords etc. removed) & then below that the parts i think I need to add in (but nor sure how/where):

 

Current contact.php code:

 

<?php
ini_set('display_errors', 1); 
$SENT = false;
if ($_POST && $_POST["name"] && preg_match("/^[a-zA-Z0-9 ]+$/i", $_POST["name"]) !== false && $_POST["email"] && preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $_POST["email"]) !== false) { 
 
try {
  include_once('class.phpmailer.php');
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->Host = "smtp.gmail.com"; // place your smtp host here
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = "ssl";
    $mail->Username = "mail@emailaddress.com "; // place your smtp username here
    $mail->Password = "Password// place your smtp password here
    $mail->Port = "465";
 
    $mail->From = $_POST["email"];
    $mail->FromName = $_POST["name"];
    $mail->AddAddress("mail@emailaddress.com ");
 
    $mail->Subject = "Enquiry from the  Website";
 

 // build the email
 $s = "The following contact form has been submitted:\n\n";
 
 $s .= "=== Customer Details =====\n";
 $s .= "Name: " .$_POST["name"]. "\n";
 $s .= "Company: " .$_POST["company"]. "\n";
 $s .= "Telephone: " .$_POST["telephone"]. "\n";
 $s .= "Email Address: " .$_POST["email"]. "\n\n";
 
 $s .= "=== Enquiry Information =====\n";
 $s .= trim($_POST["comments"])."\n\n";
 
 $s.= "Generated: " .date("Y-m-d H:i:s");
 
 $mail->Body = $s;
 $mail->WordWrap = 72; // wrap text to 72 characters
 

 //  echo "Attempting to send e-mail...";
 if ($mail->Send()) {
  $SENT = true;
 // echo "Success!";
 } else {
  $SENT = false;
 //  echo "Failed!";
 }
} catch (phpmailerException $e) {
    echo $e->errorMessage();
  } catch (Exception $e) {
    echo $e->errorMessage();
  } 
}
 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
 
<head>
 <title></title>
 <meta name="keywords" content="" />
 <meta name="description" content="" />
 <meta http-equiv="imagetoolbar" content="no" />
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
 <meta name="revisit-after" content="7 days">
 <meta name="Copyright" content="">
 <meta name="Robots" content="all">
 <meta name="language" content="en">
 <meta name="distribution" content="Global">
 
 <link rel="shortcut icon" href="/favicon.ico" />
 <link rel="stylesheet" type="text/css" href="css/print.css" media="print" />
 
 <style type="text/css" media="screen">
 <!--
 @import url(css/styles.css);
 -->
 </style>
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
 <script src="js/jquery-1.5.1.min.js" type="text/javascript"></script>
  <script src="js/global.js" type="text/javascript"></script>
 <script src="js/jquery.goomaps.js" type="text/javascript"></script>
 
 
</head>
 
<body>
 
<div id="container_header">
 <div id="header">
 
 <div id="logo"><h1><a href="/" title="Home"><span></span></a></h1></div>
 
 
    </ul>
   </li>
 
  <li><a href="contact.php" class="active">Contact Us</a></li>
  </ul>
 </div>
 
 </div>
</div>
 
<div id="container_body">
 <div id="body">
  
  <div class="clearboth"> </div>
 

  <div id="home_panel">
 
   <div id="home_bottompanel_content">
 
   <h2>Contact Us</h2>
  
   <div class="goomapsWrapper">
    <h3> Office</h3>
    <p>
   >
     <br />
     <span>T:</span> +44 0<br />
     <span>F:</span> +44 <br />
     <span>DX:</span> <br />
     <span>E:</span> <a href="mailto:mail@emailaddress.com">mail@emailaddress.com</a>
     
    </p> 
    <div id="map_canvas" class="map_canvas"></div> 
   </div>
   <div class="goomapsWrapper">
    <h3> Office</h3>
    <p>
     
     <br />
     <span>T:</span> +44 <br />
     <span>F:</span> +44 <br />
     <span>DX:</span> <br />
     <span>E:</span> <a href="mailto:mail@emailaddress.com">mail@emailaddress.com</a>
    </p>     
    <div id="map_canvas2" class="map_canvas"></div>     
   </div>   
 
   <div>

   <?php if (!$SENT) { ?>
 
   <?php if (!$SENT && $_POST) {
    echo '<p class="red">There was a problem with sending the form.<br />Please check to ensure you have filled in all the fields.</p>';
   } ?>
   <p><b>Enquiry Form</b><br />
   <span class="red">**</span> Indicates required fields</p>
   
   <script src="https://www.google.com/recaptcha/api.js" async defer></script>
   <form name="contact" action="contact.php" method="post">
   <fieldset class="conform">
   <legend>Your Details</legend><br />
   <label for="name">Name</label>
   <input id="name" type="text" size="40" value="<?php echo (isset($_POST["name"])) ? $_POST["name"] : '' ; ?>" name="name" /> <span class="red">**</span><br />
   <label for="company">Company</label>
   <input id="company" type="text" size="40" value="<?php  echo (isset($_POST["company"])) ? $_POST["company"] : '' ; ?>" name="company" /><br />
   <label for="telephone">Telephone</label>
   <input id="telephone" type="text" size="40" value="<?php echo  (isset($_POST["telephone"])) ? $_POST["telephone"] : ''; ?>" name="telephone" /><br />
   <label for="email">Email Address</label>
   <input id="email" type="text" size="40" value="<?php echo (isset($_POST["email"])) ? $_POST["email"] : ''; ?>" name="email" /> <span class="red">**</span><br />
   </fieldset>
 
   <fieldset class="conform2">
 
   <legend>Further Information</legend><br />
   <textarea id="comments" name="comments" size="40" rows="8" cols="50"><?php  echo(isset($_POST["comments"])) ? $_POST["comments"] : '' ; ?></textarea>
   </fieldset>
   <html>
 
     <div class="g-recaptcha" data-sitekey="My Site Key"></div><br>
 
   <br />
   <a href="javascript:document.contact.submit();"><img title="" height="43" alt="" src="images/submit.gif" width="102" border="0" /></a>
   </form>
   </div>
 
   <?php
    } else {
   ?>
   <p>Thank you for your enquiry. We will reply as soon as possible.</p>
   <?php
    }
   ?>
 
  </p>
 

   </div>
 
  </div>

  
 </div>
 
  <script>
   $(document).ready(function(){
   $('#map_canvas').goomaps("init", {
   center: [51.467434,0.008308],
   zoom: 16,
    clickable: true,
    draggable: true,
    scrollwheel: false,
   OverviewMapControlOptions: false,
   }).goomaps("addmarkers", [{ options: {
    position: [51.467434,0.008308]
 
    
    
   }}]);
   $('#map_canvas2').goomaps("init", {
   center: [51.462998,-0.010772],
   zoom: 16,
    clickable: true,
    draggable: true,
    scrollwheel: false,
   OverviewMapControlOptions: false,
   }).goomaps("addmarkers", [{ options: {
    position: [51.462998,-0.010772]
 
    
   }}]);  
   });
  </script>
 
</body>
</html>

This is the code I think I need to include somewhere:

 

<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
  if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
    //your site secret key
    $secret = 'My Secret Key';
    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
    $responseData = json_decode($verifyResponse);
    if($responseData->success){
        //contact form submission code goes here
 
        $succMsg = 'Your contact request have submitted successfully.';
    }else{
        $errMsg = 'Robot verification failed, please try again.';
    }
  }else{
    $errMsg = 'Please click on the reCAPTCHA box.';
  }
}
?>

Edited by Ch0cu3r
Link to comment
Share on other sites

what have you tried? we can help you with your attempted code, but only after you have made an honest attempt. if you are planning on just copy/pasting something together and dumping it on the forum with an 'it doesn't work', you won't get any more of a response than you already have.

 

if you are not at the point where you understand enough about the code or the process, so that you can even make an attempt at integrating the recaptcha check code into the correct location in your existing application, and testing the result to make sure it does what you expect, you need to instead go and study a basic php book/comprehensive tutorial. we are not here to tell you what and where to type something in your code to do what you want or to write your code for you. if you need that level of assistance, you are not ready to do this thing called programming and should just hire someone to do this for you.

Link to comment
Share on other sites

Thanks. Im not planning on just copying/pasting some code, I have tried numerous times to get it working myself but its always failing hence why I have posted on here!

 

So iv'e done the first part by adding in the recaptcha into the form as below & that is working & displaying correctly:

<script src="https://www.google.c...ecaptcha/api.js" async defer></script> 
    <form name="contact" action="contact.php" method="post">
    <fieldset class="conform">
    <legend>Your Details</legend><br />
    <label for="name">Name</label>
    <input id="name" type="text" size="40" value="<?php echo (isset($_POST["name"])) ? $_POST["name"] : '' ; ?>" name="name" /> <span class="red">**</span><br />
    <label for="company">Company</label>
    <input id="company" type="text" size="40" value="<?php  echo (isset($_POST["company"])) ? $_POST["company"] : '' ; ?>" name="company" /><br />
    <label for="telephone">Telephone</label>
    <input id="telephone" type="text" size="40" value="<?php echo  (isset($_POST["telephone"])) ? $_POST["telephone"] : ''; ?>" name="telephone" /><br />
    <label for="email">Email Address</label>
    <input id="email" type="text" size="40" value="<?php echo (isset($_POST["email"])) ? $_POST["email"] : ''; ?>" name="email" /> <span class="red">**</span><br />
    </fieldset>

 

   <fieldset class="conform2">

 

   <legend>Further Information</legend><br />
    <textarea id="comments" name="comments" size="40" rows="8" cols="50"><?php  echo(isset($_POST["comments"])) ? $_POST["comments"] : '' ; ?></textarea>
    </fieldset>
    <html>

 

     <div class="g-recaptcha" data-sitekey="My Site Key"></div><br>
  
    <br />
    <a href="javascript:document.contact.submit();"><img title="" height="43" alt="" src="images/submit.gif" width="102" border="0" /></a>
    </form>
    </div>

I have also created the verify code as in first post but I cant get this part to work. I have tried saving this in a separate php file, & referencing that in the form but then when I click on submit, it just goes to a blank page. I ideally want it so that when I click submit it stays on the same page with just a thank you or error message as it does now so am guessing I need to add the verify code into the existing page but am not sure where? the form currently works regardless of whether I tick the recaptcha or not.

Link to comment
Share on other sites

If I tick the recaptcha i get the following:

array(6) { ["name"]=> string(0) "" ["company"]=> string(0) "" ["telephone"]=> string(0) "" ["email"]=> string(0) "" ["comments"]=> string(0) "" ["g-recaptcha-response"]=> string(1017) "03AHJ_VuvDRUvVoCu1XXhz2D-y3ZjdKu19l-sDeF9Gq-lOeK1fbV9IPaVzW6xo5QuQBF6zJ4O8mR4EHP6_liWh9F5uJ7SVRXhjXfrUHRcRU2DlyGjixgfMd1hDac98FwAYmao_wvYs_nQ4weMyuAL8OVQ4Hc1xirOr23YC5bk79svzmpsH6-oFRdf3zQHqwpDL17MHtSQHE18cD0mgQG4-z4WLfn6Vks9RERgsb6Ye_bo7hS3iPXvQF6U23Fni1FfRnuEF3g6L4IhVni0Li73G6LKBj74VQggnJjLsKBa-EdAOwNvuxbr7hP8opc0NjipzwLnT0h3lEBLgf3np8lhE3M21VGkBO3hvdu4JoShTB79kKQdMWXyh2JeEazw_Vs2DnZie2thjgR7mDuhGp8-jgX3yj3ugtvUWi1NZM9-sksD31cF4VjHfe7vMEp27S1CjP_tLp-W38vADUuwI64In9kllzGRrJNsq9hteDCH1DKTi3T8X-rCm4Yt1GNH6_XGrwkwC4u2oj0_Yzeo7_VoBaZUIKL3WVhQpaIo-bAj6IxU-JWGlP3gXh8fBbH__xsFK8zm4vokbcVcBhC7fcEvxQihWNvOU7DYcrK1koxcvvWUqBL-aXeZZ6BRxNWSgzKdMQjIPOvyNCS1aOEagrRbYTQSH1evP0dvvEuuOF6JNC7d_blLg9PENcqJMlYYl_ILBb0OCHNLbK2YJ9pnJV73Db4KKExwOT1eW7D06ECA6wyn_bkFOVfObZiGJPv2AZ_t5H5OgNinkceK-kNcge9e76cKZRe6Rsb-dWULJfbMOIucGhxHCl_3cj0NX6ZVoqmSxyj8KK8wPEjzD4kWLQxJ948mIRbeoQEjVvue1y2MnM-8CLYJaC07u9dGsP-QZnli7AbFcg8n_XHx1OylDtsjRUJ4_91lBDeywI5eeneisqo-axtiNZBcNciygsTIrxNWkOwjr0obJsFIk2lk6aeQyq4EfeQOQZcVJrEpgQFFTrQk_4yF5eru22tc" } 
Link to comment
Share on other sites

Yes thats correct ive put my secret key in there but I still receive the invalid recaptcha message. If I dont tick it i get the please re enter your recaptcha.

 

 

What could be telling it that the entry is wrong? Do I need to change the contact.php code somewhere?

Link to comment
Share on other sites

Weird you are getting  a NULL result.

 

Change the code to

<?php

if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
    {   
        $captchaurl = "https://www.google.com/recaptcha/api/siteverify";

        // values for verifying recaptha
        $captcha_params = array(
            'secret'   => 'secret-key-here',
            'response' => $_POST['g-recaptcha-response'],
            'ip'       => $_SERVER['REMOTE_ADDR']
        );

        $curl_init = curl_init();
        curl_setopt($curl_init, CURLOPT_URL, $captchaurl);
        curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);

        // send recapture values via POST
        curl_setopt($curl_init, CURLOPT_POST, count($captcha_params));
        curl_setopt($curl_init, CURLOPT_POSTFIELDS, $captcha_params);

        curl_setopt($curl_init, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($curl_init);
        curl_close($curl_init);

        echo "Curl Response: ";
        var_dump($response);

        if($response == FALSE)
        {
            echo "<p>Curl Error: " . curl_error();
        }
        else
        {
            $result = json_decode($response, true);
            echo "Recaptha Result: "
            var_dump($result['success']);
        }
    }
} 

Whats is the output now?

Edited by Ch0cu3r
Link to comment
Share on other sites

This is the current code for submit.php:

<?php

if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
    {   
        $captchaurl = "https://www.google.com/recaptcha/api/siteverify";

        // values for verifying recaptha
        $captcha_params = array(
            'secret'   => 'my key',
            'response' => $_POST['g-recaptcha-response'],
            'ip'       => $_SERVER['REMOTE_ADDR']
        );

        $curl_init = curl_init();
        curl_setopt($curl_init, CURLOPT_URL, $captchaurl);
        curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);

        // send recapture values via POST
        curl_setopt($curl_init, CURLOPT_POST, count($captcha_params));
        curl_setopt($curl_init, CURLOPT_POSTFIELDS, $captcha_params);

        curl_setopt($curl_init, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($curl_init);


        echo "Curl Response: ";
        var_dump($response);

        if($response == FALSE)
        {
            echo "<p>Curl Error: " . curl_error($curl_init);
        }
        else
        {
            $result = json_decode($response, true);
            echo "Recaptha Result: ";
            var_dump($result['success']);
        }
        curl_close($curl_init);
    }
} 


Link to comment
Share on other sites

one would hope that the recaptcha api would return a unique error for each different thing that could go wrong, but perhaps not.

 

the ip address in the data to the api is optional, so if it's not being put into the data, it doesn't matter, but what if it is present and it's not the same value from the client when the client solved the captcha? if the client being used for testing is on the same local network with the server, the ip address that the server gets in $_SERVER['REMOTE_ADDR'] will be a local ip. the ip address that the recaptcha api saw when the captcha was solved would be the public network ip address. try removing the ip key/value pair from the $captcha_params.

 

next, i wonder what happens if you submit the same curl request twice, which would happen if your .php page is being requested twice? a lot of clients request a page twice. perhaps the output being seen is that due to a second request, and since the recaptcha api has already seen and responded to any specific 'g-recaptcha-response' value, perhaps it returns a null in this case? i would add code in your .php page that logs some information (see file_put_contents() with the FILE_APPEND flag) from the client request and from the curl response each time it runs. this will let you see if there are multiple requests being made for each form submission and if the curl response is always the same.

 

you can also try using an 'official' recaptcha php class (there's a link on the recaptcha/google page.) perhaps it is setting curl options that can have an affect (i saw some code that's setting an ssl verify host parameter to a false value.)

 

however, getting a null from a curl request seems more like a communication problem. the url that's being used would require that the server have open_ssl installed. what does the output from a phpinfo() statement show for the SSL entry under the CURL section?

Edited by mac_gyver
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.