Cant get Recaptcha to work on contact form

Hi, as the title suggests, im trying to add recaptcha to our existing contact form. I’ve 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! I have created the verify code 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? Please see my current code below (emails/passwords etc. removed) & then below that the verify parts I think I need to add in (but nor sure how/where):

Current Contact PHP Form:

[php]<?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 = "[email protected] "; // 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("[email protected] ");


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

?>

</ul>
</li>
  • Contact Us
  •  

    Contact Us

    <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:[email protected]">[email protected]</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:[email protected]">[email protected]</a>
     </p>     
     <div id="map_canvas2" class="map_canvas"></div>     
    </div>   
    
    <?php if (!$SENT) { ?>
    
    <?php if (!$SENT && $_POST) { echo '

    There was a problem with sending the form.
    Please check to ensure you have filled in all the fields.

    '; } ?>
    <p><b>Enquiry Form</b><br />
    <span class="red">**</span> Indicates required fields</p>
    
    <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>
    
    Further Information
    <?php echo(isset($_POST["comments"])) ? $_POST["comments"] : '' ; ?>
     <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
     }
    ?>
    
    </div>
    
    [/php]

    The Verify code I need to add in:

    [php]<?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.c…ha-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.’;
    }
    }
    ?>[/php]

    I’m sure someone will help you out on this, but have you considered using hidden captcha? I use it in my contact form, what it basically boils down is it fools bots to think it needs to fill in a a field, whereas a user would skip it (if they have JavaScript turned off).

    Here’s what I mean :
    [php]

    <?php echo isset($success) ? $success : 'Contact Form'; ?>
    First Name

    Last Name

    Email Address


    Leave blank







    comment

    pricing

    order info
            <label class="textareaLabel" for="message">Message</label>
            <textarea id="message" name="comment" placeholder="Enter message here..."></textarea>
            <input type="submit" name="submit" value="submit">
        </fieldset>
    </form> [/php]
    

    You would just do a reverse validation to the subject field (in this example), for example:

    [php]if (isset($_POST[‘subject’] && !empty($_POST[‘subject’])) {
    echo “Congrats, Email successfully sent!”; // :wink:
    }[/php]

    It’s not foolproof (nothing is really foolproof, for I have even seen regular captcha get bypassed), but I does the trick for me for I don’t get that much spam email, plus it takes the burden of the user guessing what the darn word or number is. :wink: Just something to think about.

    Note: the fields has to be something that is believable, such as subject, title, message, content…etc in order to fool the bot(s).

    thanks but id rather stick with the Google one if I can get it working! I’ve now changed the verify code to use curl, but its still not working, I receive invalid recaptcha message every time, regardless of whether I tick the box or not:

    [php]<?php

    function json_status($status)
    {
    echo json_encode(array(‘status’ => $status));
    }

    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);
    
        $results = curl_exec($curl_init);
        curl_close($curl_init);
    
        $results = json_decode($results, true);
    
        if($results['success'])
        {   
            json_status('success');
        }
        else
        {
            json_status('Invalid reCAPTCHA code');
        }           
    }
    else
    {
        json_status('Please re-enter your reCAPTCHA.'); 
    }
    

    }
    [/php]

    Anyone have any thoughts on this one?

    I’d strongly suggest using their PHP client, you can

    [ul][li]find it via packagist[/li]
    [li]download it with composer (or directly from github)[/li]
    [li]and use it like this[/li][/ul]

    [php]<?php
    $recaptcha = new \ReCaptcha\ReCaptcha($secret);
    $resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
    if ($resp->isSuccess()) {
    // verified!
    } else {
    $errors = $resp->getErrorCodes();
    }[/php]

    Ok so I can find the files etc. but no idea how to use it via composer? I cant install composer as it askes for the location of php.exe?

    Would it be easier to just get the code & copy this in manually i.e. use the above to replace my existing verify.php code or does it not work like that?

    the instructions for downloading directly from github should get you going

    yeah I’ve downloaded it, but then what? Do I just copy the Recaptcha.php code from the src folder & modify that & use instead of my verify code?

    copy/paste from https://github.com/google/recaptcha#direct-download-no-composer

    Direct download (no Composer)

    If you wish to install the library manually (i.e. without Composer), then you can use the links on the main project page to either clone the repo or download the ZIP file. For convenience, an autoloader script is provided in src/autoload.php which you can require into your script instead of Composer’s vendor/autoload.php. For example:

    [php]require(’/path/to/recaptcha/src/autoload.php’);
    $recaptcha = new \ReCaptcha\ReCaptcha($secret);[[/php]

    you use it like the code I pasted before, as you can see the last code line in their direct download instructions is the first line in the code I pasted previously. Including the autoloader and instantiating the class makes the recaptcha client available.

    Sponsor our Newsletter | Privacy Policy | Terms of Service