Implement Google reCAPTCHA on contact form

Hello everybody :slight_smile:

After some time searching for a solution I found your site and one of your articles which is very similair to my problem.

My Task: I have a contact form on my homepage to which I would like to add a Google reCAPTCHA.

Problem: The contact form works without a CAPTCHA, but as soon as I try to implement one, it doesn’t work at all.

The contact form is the following:

<form id="contact-form" method="POST" action="send_email.php" role="form">
  <div class="form-group">
    <input type="text" placeholder="Your Name" class="form-control" name="name" id="name">
  </div>
  <div class="form-group">
    <input type="email" placeholder="Your Mail" class="form-control" name="email" id="email" >
  </div>
  <div class="form-group">
    <input type="text" placeholder="Subject" class="form-control" name="subject" id="subject">
  </div>
  <div class="form-group">
    <textarea rows="6" placeholder="Your message" class="form-control" name="message" id="message"></textarea>
  </div>
  <div class="g-recaptcha" data-sitekey="<--PUBLIC SITE KEY-->"></div> 
  <div id="submit">
    <input type="submit" id="contact-submit" class="btn btn-default btn-send send-button" name="contact-submit"     value="Send message">
  </div>
</form>

After the submit button is pressed, it will go to send_email.php. This File is a combination out of the part I added for the CAPTCHA:

<?php

echo "1";

	$yoursecret = "<--SECRET SITE KEY-->";
	
echo "2";

$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=". $yoursecret."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
	$googleobj = json_decode($response);
	$verified = $googleobj->success;

echo "3";

	if ($verified === true){

echo "4";

The normal part which works on itself:

		if(isset($_POST['email'])) {
			
			$email_to = "my@mail.com";
			$email_subject = "Contact Form";
	
echo "5";

			function died($error) {
				// error
				echo "Following mistake appeared:<br /><br />";
				echo $error."<br /><br />";
				echo "Please check your submission.<br /><br />";
				die();
			}
	
echo "6";

			if(!isset($_POST['name']) ||
			!isset($_POST['email']) ||
			!isset($_POST['subject']) ||
			!isset($_POST['comments'])) {
				died('A Problem appeared.');       
			}
	
echo "7";

			$name = $_POST['name']; // required
			$email_from = $_POST['email']; // required
			$subject = $_POST['subject']; // not required
			$comments = $_POST['comments']; // required
	
echo "8";

			$error_message = "";
			$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
			if(!preg_match($email_exp,$email_from)) {
				$error_message .= 'Your mail is not valid.<br />';
			}
	
echo "9";

			$string_exp = "/^[A-Za-z .'-]+$/";
			
			if(!preg_match($string_exp,$name)) {
				$error_message .= 'Your name is not valid.<br />';
			}
	
echo "10";

			if(strlen($comments) < 2) {
				$error_message .= 'Your message is empty or not valid.<br />';
			}
	
echo "11";

			if(strlen($error_message) > 0) {
				died($error_message);
			}
	
echo "12";

			$email_message = "Contact Form \n\n";

			function clean_string($string) {
				$bad = array("content-type","bcc:","to:","cc:","href");
				return str_replace($bad,"",$string);
			}
	
echo "13";

			$email_message .= "Name: ".clean_string($name)."\n";
			$email_message .= "Email: ".clean_string($email_from)."\n";
			$email_message .= "Subject: ".clean_string($subject)."\n";
			$email_message .= "Comments: ".clean_string($comments)."\n";
	
echo "14";

			$headers = 'From: '.$email_from."\r\n".
			'Reply-To: '.$email_from."\r\n" .
			'X-Mailer: PHP/' . phpversion();
			
			@mail($email_to, $email_subject, $email_message, $headers); 
	
echo "15"; 

and the end of the part added for the CAPTCHA:

                        died('SUCCESSFUL');
		}
		else{
	
echo "16";

			died('ERROR');
		}
	}

I also added:

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

Thank you for all your help!

Precisely what does it do when you add the CAPTCHA? Does it not draw the form, does it draw a blank page when you submit, does it throw your error message, or any other error message(s), or does it seem to work but not send the mail?

What do the instructions say about setting up/changing <--PUBLIC SITE KEY--> and <--SECRET SITE KEY-->?

Also, not related to your query, you should not be relying on placeholders to inform users what they are expected to enter there. For one thing, it is not accessible. Not all browsers and screenreaders understand placeholder. Also, it can be unhelpful to people using auto-complete.

One other thing using die() after you have displayed a message is rather sloppy programming.

It just draws a blank page and also doesn’t send the mail.

I inserted my personal keys but changed it again for being able to publish it here. In the original code they’re in the code. :slight_smile:

Thank you for your hint with the placeholders.

How would you recommend me to replace die()?

OK, if it’s giving a blank page you need to figure out how far down your PHP it’s getting before it dies, if anywhere. I’d add echo() statements through the code, enable error displays while debugging and so on, but there are many ways to do that. Is it getting the correct captcha entry from the form, and if you then try to open the google url manually with that information and your other details, does that work?

I did so through my original code as well as through the code above. Unfortunately there weren’t any numbers displayed at all.

I tried to, but probably I wasn’t able to create the url on my own. How would you do this? I did it like this =>
https://www.google.com/recaptcha/api/siteverify?secret=“MYCODE”&response=“g-recaptcha-response”&remoteip=“REMOTE_ADDR”

But if I do so there is only the following displayed:

{
  "success": false,
  "error-codes": [
    "invalid-input-response"
  ]
}

I propose the mistake is somewhere here:
“g-recaptcha-response”&remoteip=“REMOTE_ADDR”

Thank you so much for your help!

It can be tricky to do, but worth persevering with when you have the time. I’m not sure it would work within a function as you have it. Without the function you could probably use elseif and else after your if clause to achieve the result.

I assume that you’re actually entering the captcha “answer”, not actually the string “g-recaptcha-response”?

In any case, that shows that when you try to get to the URL manually you get a response. And if none of your numbers show, that suggests that it isn’t running the PHP code at all.

Presumably you have the js linked at the top of your html, otherwise it wouldn’t draw the CAPTCHA. The code you use doesn’t look much like the sample code shown on the Google API reference, but it does look very similar to the code here: https://codeforgeek.com/2014/12/google-recaptcha-tutorial/

Thank you both for your very helpful input! And I’m so sorry for not answering earlier.

I will definitely try this option and let you know if and how it worked.

I changed this part:

$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=". $yoursecret."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);

into this:

$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=". $yoursecret."&response=".$captcha."&remoteip=".$ip);

and also added the following:

if(isset($_POST['g-recaptcha-response'])){
          $captcha=$_POST['g-recaptcha-response'];
        }
        if(!$captcha){
          echo '<h2>Please check the the captcha form.</h2>';
          exit;
        }
	$ip = $_SERVER['REMOTE_ADDR'];

I filled out the form with valid informations. As a result there are now the numbers 1, 2, 3, 4, 5 and 6 as well as the messages “Following mistake appeared:” “A Problem appeared.” “Please check your submission.” displayed onto the (not anymore) blank page. According to this the PHP code should run.

Yes I did so.

That’s correct as well. I took this code as a source and modified it so it fits my needs.

1 Like

That error message comes from here:

if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['subject']) ||
!isset($_POST['comments'])) {
	died('A Problem appeared.');       
	}

Spot the problem:

<textarea rows="6" placeholder="Your message" class="form-control" name="message" id="message"></textarea>

Thank you so much! :raised_hands:

I’m sorry for such an embarrassing mistake.

Thanks again :smiley:

No problem - sometimes the more you look at something, the less obvious things are.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.