How to create an email form with PHP with a reCAPTCHA

This guide will show you how to create a contact form with PHP that includes a captcha requirement to submit, using Google reCAPTCHA. Before you start, you’ll need to set up your site with Google to be able to use the Google reCAPTCHA API.

For the purposes of this guide we’re using reCAPTCHA v2 with checkbox widget.

How to register a site for a reCAPTCHA

You can set up a reCAPTCHA using a Google account and logging into your admin console. You can do this from here.

Once logged in you can now register your site with Google with the following steps:

  1. Enter Label to help identify the site in the future.
  2. Choose the type of reCAPTCHA you wish to use. You can find out more about the different options here.
  3. Under the Domains section enter your domain name.
  4. Under the Owners section choose the emails of the owners of your site. Your Gmail will already be listed but you can add further emails below it.
  5. Click to Accept the reCAPTCHA Terms of Service and choose if you would like to Send alerts to owners.
  6. Click SUBMIT.
  7. You will now be presented with a SITE KEY and SECRET KEY; you will need these to activate the captcha on your site. Don’t worry if you close the page, you can get the keys again from the settings page.

Create the web form

Now we need to create a HTML form, we'll keep the form simple by just asking for an email address and including a text box for comments. We’ll need to insert a line into the HTML head section to include a JavaScript file for the Google reCAPTCHA API and a line within the form to insert the reCAPTCHA widget and include our API key. Here’s the HTML form:

	<html>
	<head>
	<title>Simple Feedback Form</title>
	<style>label{display:block;}</style>
	<script src='https://www.google.com/recaptcha/api.js' async defer></script>
	</head>
	<body>

	<form method="post" action="/feedback_form.php">
	<label>Email Address<label>
	<input type="text" name="email_address" size="40">
	<label>Your Feedback</label>
	<textarea name="feedback" cols="50" rows="10"></textarea>
	<div class="g-recaptcha" data-sitekey="YOUR SITE KEY"></div>
	<input type="submit" name="send" value="Submit">
	</form>

	</body>
	</html>

This form will send some parameters to our PHP script: email_address, feedback and will include data to verify the captcha submission.

You’ll need to replace the text ‘YOUR SITE KEY’ in the following line with your Google reCaptcha site key:

	<div class="g-recaptcha" data-sitekey="YOUR SITE KEY"></div>

Save this file as feedback_form.html and upload it to the web folder for your site.

Verifying the captcha response

First we’ll provide an example of how to verify the captcha response in a simple PHP script.

We create 3 PHP variables to store the data received from our form: $email, $feedback and $captcha:

The $email and $feedback variables will store the data from the fields filled out when submitting the form, the $captcha variable will store the captcha response:

	<?php
	$email=$_POST['email_address'];
	$feedback=$_POST['feedback'];
	$captcha=$_POST['g-recaptcha-response'];

If the captcha response from the form is empty, it should indicate the captcha hasn’t been filled out and we’ll return an error message using the echo command:

	if(!$captcha){
			echo '<p>Please complete the captcha to submit the form.</p>';
			exit;
	}

If the $captcha variable isn’t empty, then we’ll proceed to verify that captcha has been completed successfully

	else {
	$secretKey = "YOUR PRIVATE KEY";
	$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
	$response = file_get_contents($url);
	$responseKeys = json_decode($response,true);
	}

You’ll need to replace the text “YOUR PRIVATE KEY” with your reCAPTCHA Secret Key. The captcha verification response is formatted as JSON – the rest of the script above will verify the JSON response from the Google reCAPTCHA API.

If the response indicates the captcha was successfully verified, then we display a message to indicate this, if this fails it indicates the script is being accessed without successful verification and we display an error message:

	if($responseKeys["success"]) {
	echo '<p>Your submission was successful</p>';
		#add your PHP mail script here
	} else {
	echo '<p>Your submission attempt has been blocked by anti-spam measures.</p>';
	}
	?>

Here’s the whole script:
	<?php
	$email=$_POST['email_address'];
	$feedback=$_POST['feedback'];
	$captcha=$_POST['g-recaptcha-response'];
	if(!$captcha){
	echo '<p>Please complete the captcha to submit the form.</p>';
	exit;
	}
	else {
	$secretKey = "YOUR PRIVATE KEY";
	$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
	$response = file_get_contents($url);
	$responseKeys = json_decode($response,true);
	}
	if($responseKeys["success"]) {
	echo '<p>Your submission was successful</p>';
			#add your PHP mail script here
	} else {
	echo '<p>Your submission attempt has been blocked by anti-spam measures.</p>';
	}
	?>

Now we’ve created a script to verify if the captcha field has been completed on any form submissions, you might have noticed that the script doesn’t actually do anything else with the submitted message.

We’ll need to make some additions to the script to send an email with the contents of the form submission. If you’ve followed our guide on how to create an email form with PHP, we’ll work with the email script provided in this guide – so that our captcha secured form can send an email.

The Final Script

The final script below shows a basic way to get the form contents emailed to you. It includes a function to filter user input to try and block script injection, but doesn’t have any of the refinements of a more professional script – like input validation to check that a valid email address has been entered.

We’ve added some comments (lines beginning with #) to indicate what each section of code is doing:


<?php
	#storing the POST data from form submission
	$email_address=$_POST['email_address'];
	$feedback=$_POST['feedback'];
	$captcha=$_POST['g-recaptcha-response'];
	#if the captcha isn't filled out
		if(!$captcha){
			echo '<h2>You need to complete the captcha!</h2>';
			exit;
		}		
	#verifying the captcha response
	$secretKey = "6LeGmbcUAAAAANmiEuwxPXc5BY5FK4rA0ckEg5sA";
	$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
	$response = file_get_contents($url);
	$responseKeys = json_decode($response,true);
		#if captha response is successful then send our email
		if($responseKeys["success"]) {
			#Filter user input/try to block script injection
			function filter_email_header($form_field) {
			return preg_replace('/[\0\n\r\|\!\/\<\>\^\$\%\*\&]+/','',$form_field);
			}
			$email_address  = filter_email_header($email_address);
			#Send email
			$headers = "From: $email_address\n";
			$sent = mail('test@lcn.com', 'Feedback Form Submission', $feedback, $headers);
			if ($sent) {
			echo '
				<html>
				<head>
				<title>Thank You</title>
				</head>
				<body>
				<h1>Thank You</h1>
				<p>Thank you for your feedback.</p>
				</body>
				</html>
				';
			} else {
			echo '
				<html>
				<head>
				<title>Something went wrong</title>
				</head>
				<body>
				<h1>Something went wrong</h1>
				<p>We could not send your feedback. Please try again.</p>
				</body>
				</html>
				';
			}
		} 
		#if access to script is attempted without captcha response
		else {
			echo '
				<html>
				<head>
				<title>No spam!</title>
				</head>
				<body>
				<h1>Something went wrong</h1>
				<p>Spamming this form script is not allowed.</p>
				</body>
				</html>
			';
		}
?>

Replace the place-holder address 'you@domain.com' with the email address that you want to receive form submissions to.

Save the script as feedback_form.php and upload it to the same location as the contact form HTML page.

That’s it! Your contact form should now function with reCAPTCHA.

Please Note: The above script is for example purposes to help advise how to add a reCAPTCHA to your contact form.

Check out some of our related guides

Need a hand? Search over a hundred step-by-step support guides