Using an html form for a "contact us". This passes name, email, & message to a .php script and it works well. Add the Google recaptua v2 to this form gives a http 500 Error. This post and the code have been edited to reflect the KaplanKomputing tutorial suggested by Chris White.

You can visit the working form without recaptcha, and nonworking recaptcha here: https://coinsandhistory.com#contact

The "Google site key" I'll call here "XXXX-Google-site" and "YYYY-Google-secret".

1st the contact form html, you don't need the css styling nor the stripslashes from the tutorial.

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

<link rel="stylesheet" href="../css/send-mail.css">
</head>

<body>
<!-- https://stackoverflow.com/questions/27188436/html-php-contact-form- 
email/55962553 -->
<!-- https://kaplankomputing.com/blog/tutorials/
recaptcha-php-demo-tutorial/ -->
<form action="send-mail_SO2_recapt.php" method="post" 
enctype="multipart/form-data" name="myemailform">
<div>
<span>Name &nbsp;</span>
<input type="text" name="name" value="" placeholder="Your Name">
</div>
<div>
<span>Email &nbsp;</span>
<input type="email" name="web_email" autocapitalize="off" 
autocorrect="off" 
value="" placeholder="[email protected]">
</div>

<div>
<span>messgae &nbsp;</span>
<textarea name="message" placeholder="message"></textarea>
</div>

<!--  Google v2 Recaptua Form   -->
<div class="g-recaptcha" data-sitekey="XXXX-Google-site"></div>
<br/>

<div class="code">
<button><input type="submit" name="submit" value="Send"></button>
</div>
<i class="clear" style="display: block"></i>
</div>
</form>
</body>
</html>

And then the send-mail.php script. I called mine "send-mail_SO2_recapt.php".

<?php
/* error reporting, should rmv from working form */
error_reporting(E_ALL);
ini_set('display_errors', 1);

if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST["name"];
$visitor_email = $_POST['web_email'];
$message = $_POST["message"];
$response = $_POST["g-recaptcha-response"];

//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are needed!";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}

$url = "https://google.com/recaptcha/api/siteverify";
$data = array(
"secret" => "YYYY-Google-secret",
"response" => $_POST["g-recaptcha-response"]);
$options = array(
"https" => array (
"method" => "POST",
"content" => https_build_query($data)
)
);
$context  = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);

if ($captcha_success=>success==false) {
echo "<p>You are a bot! Go away!</p>"; }
else if ($captcha_success=>success==true) {
echo "<p>You are not not a bot!</p>";   }

// $email_from = '[email protected]';//<== update the email address
$email_from = "$visitor_email";
$email_subject = "New Form submission";
$email_body = "You have received a new message from $name.\n".
"sender's email:\n $email_from\n".
"Here is the message:\n $message";

$to = "[email protected]";   //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank_you_SO2.html');
exit;

// Function to validate against any email injection attempts
?>

If you supply code samples, please indicate what form it is: eg html, php, javascript. I can't believe I'm the 1st person to try to use a simple Google recaptua in a contact form but this question doesn't appear plainly anywhere.

2 Answers

1
Galzor On

i see number of errors in your code. try the following code and see if it works, it is tested and working for me. it is not based on your followed tutorial and uses curl for verification instead.

Your biggest mistakes i think are that there is no isInfected function defined, => in place of -> and sometime file_get_contents doenst work on all servers.

HTML:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="" method="post">
  <div>
    <span>Name</span>
    <input type="text" name="name" placeholder="Your Name" required>
  </div>
  <div>
    <span>Email</span>
    <input type="email" name="web_email" placeholder="[email protected]" required>
  </div>
  <div>
    <span>Messgae</span>
    <textarea name="message" placeholder="message" required></textarea>
  </div>
  <!--  Google v2 Recaptcha Form   -->
  <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
  <div class="code">
    <input type="submit" name="submit" value="Send">
  </div>
</form>

PHP CODE:

<?php
//check form is submitted
if( isset($_POST['submit']) ){

  // get values
  $error = '';
  $name          = $_POST["name"];
  $visitor_email = $_POST['web_email'];
  $message       = $_POST["message"];

  //Validate first
  if(empty($name)||empty($visitor_email)) {
    $error = "Name and email are needed!";
  }

  //handle captcha response
  $captcha = $_REQUEST['g-recaptcha-response'];
  $handle = curl_init('https://www.google.com/recaptcha/api/siteverify');
  curl_setopt($handle, CURLOPT_POST, true);
  curl_setopt($handle, CURLOPT_POSTFIELDS, "secret=YOUR_SECRET_KEY&response=$captcha");
  curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($handle);
  $explodedArr = explode(",",$response);
  $doubleExplodedArr = explode(":",$explodedArr[0]);
  $captchaConfirmation = end($doubleExplodedArr);
  print_r($doubleExplodedArr);
  if ( trim($captchaConfirmation) != "true" ) {
    $error = "<p>You are a bot! Go away!</p>";
  }

  if( empty($error) ){ //no error
    // mail than
    $to = "[email protected]";
    $email_subject = "New Form submission";
    $email_body = "You have received a new message from ".$name.".\n".
    "sender's email:\n ".$visitor_email."\n".
    "Here is the message:\n ".$message;
    $headers = "From: ".$visitor_email." \r\n";
    $headers .= "Reply-To: ".$visitor_email." \r\n";
    //Send the email!
    $mail_check = mail($to,$email_subject,$email_body,$headers);
    if( $mail_check ){
      // echo "all is well. mail sent";
      header('Location: thank_you.html');
    } else {
      echo "mail failed. try again";
    }
  } else {
    echo $error;
  }
}
?>
1
Nicholas Bourbaki On

Here is an answer which worked for me. I'd like to really thank Galzor as his answers helped me a lot. The base Code I got from Code Geek and I added stuff here to add in the form. This format hopefully eliminated the confusion on exactly what to include in the Google "SITE-KEY" and "SECRET-KEY" as it gets them as variables before processing them in a string. These are actually 40 character strings. The sucessful captcha goes to a landing page.

This is the HTML send-mail_form.html

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

</head>

<body>
<!-- form goes in the body of HTML  -->
<form action="send-mail_form.php" method="post">

<div>
<span>Name</span>
<input type="text" name="name" value="" placeholder="Your Name" required>
</div>

<div>
<span>Email</span>
<input type="email" name="web_email" placeholder="[email protected]" required>
</div>
<div>
<span>Messgae</span>
<textarea name="message" placeholder="message" required></textarea>
</div>

<!--  Google v2 Recaptcha Form   -->
<div class="g-recaptcha" data-sitekey="SITE-KEY"></div>
<div class="code">
<input type="submit" name="submit" value="Send">
</div>
</form>

</body>
</html>

And this will be the called send-mail_form.php. I won't bother with showing the thank_you_SO2.html here.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$web_email;$message;$captcha;
// check form is submitted
if(isset($_POST['web_email']) ){

// get values
$name=            $_POST["name"];
$visitor_email=   $_POST['web_email'];
$message=         $_POST['message'];

//Validate first
if(empty($name)||empty($visitor_email)) {
$error = "Name and email are needed!";
}

if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}

if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}

$secretKey = "SECRET-KEY";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . 
urlencode($secretKey) .  '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
// echo '<h3>Thanks for contacting us</h3>';

// mail then
$to = "[email protected]";
$email_subject = "CG Recaptcha Form2 submission";
$email_body = "You have received a new message from ".$name.".\n".
"sender's email:\n ".$visitor_email."\n".
"Here is the message:\n ".$message;

//Send the email!
$mail_check = mail($to,$email_subject,$email_body);
if( $mail_check ){
// echo "all is well. mail sent";
header('Location: thank_you_SO2.html');
}
else {
echo '<h2>You are a spammer ! Go Away</h2>';
}
}
}
?>

There are some unneccesary items, the error checking at the top can probably be removed. Also will the Google site verify will work with https://google.com/recaptcha/api/siteverify?secret=.... ? Actually on testing it seems to fail sometimes without the www so perhaps best to keep it.