Simple PHP Contact Form With Google reCaptcha – Free Code Download

Welcome to a quick tutorial on how to create a simple PHP contact form with Google reCaptcha. So you want to put a contact form on your website, but is afraid of spam?

The simplified steps to creating a contact form secured by Google reCaptcha are:

  1. Register the website at Google reCAPTCHA admin panel, obtain the site key and secret key.
  2. Create the HTML contact form, load the reCAPTCHA Javascript library, and embed the site key.
  3. Upon submission, send the captcha response and secret key to the reCAPTCHA server for validation – If verified, send the contact form to the admin via email.

Yep, that covers the basics. While this may seem rather confusing at first, it is actually a pretty simple process… Just a hassle to run through the admin stuff. Read on for an actual example!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes PHP Contact Form Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code in a zip file – I have released it under the MIT License, so feel free to build on top of it if you want to.

 

QUICK NOTES

  • Register your websites with Google reCaptcha first.
  • Insert the site key into 2-form.php and secret key into 3-process.php.
  • Change $mailTo to your own in 3-process.php.
  • That’s all. Launch 2-form.php in the browser.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

PHP CONTACT FORM

All right, let us now get started with the PHP contact form.

 

STEP 1) REGISTER SITE AT GOOGLE RECAPTCHA

Go to the Google reCAPTCHA admin panel, and simply register your website. Please take note that if you want to test the captcha on your local machine, you have to add localhost and/or 127.0.0.1 (IPv4) ::1 (IPv6) into the domains list.


When you are done with the registration, Google will throw you a site key and secret key. Don’t have to copy them down on a piece of paper… We can always check back in the admin panel to get them later. 😆

 

 

STEP 2) THE CONTACT FORM 

2-form.php
<!-- (A) GOOGLE RECAPTCHA API -->
<script src='https://www.google.com/recaptcha/api.js'></script>
 
<!-- (B) PROCESS + NOTIFICATIONS -->
<?php
if (isset($_POST['name'])) { 
  require "3-process.php"; 
  echo $error=="" 
    ? "<div id='notify'>OK</div>"
    : "<div id='notify'>$error</div>";
}
?>
 
<!-- (C) CONTACT FORM -->
<form id="cform" method="post">
  <h1>Contact Us</h1>
 
  <label>Your Name</label>
  <input type="text" name="name" required/>
 
  <label>Email Address</label>
  <input type="email" name="email" required/>
 
  <label>Message</label>
  <textarea name="message" required></textarea>
 
  <!-- (D) CAPTCHA - CHANGE SITE KEY! -->
  <div class="g-recaptcha" data-sitekey="SITE KEY"></div>
 
  <input type="submit" value="Submit"/>
</form>

This may seem pretty intimidating to some beginners, but keep calm and look closely.

  • A – We are simply loading the reCaptcha Javascript library here.
  • B – This part will run only when the form is submitted, using 3-process.php to verify the captcha and send the contact form via email.
  • C – Self-explanatory. The contact form itself.
  • D – Where you want the captcha to be at. Remember to insert the site key.

That’s all for the HTML form.

 

 

STEP 3) PHP PROCESSING

3-process.php
<?php
// (A) PROCESS STATUS
$error = "";

// (B) VERIFY CAPTCHA
$secret = 'SECRET KEY'; // CHANGE THIS TO YOUR OWN!
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=".$_POST['g-recaptcha-response'];
$verify = json_decode(file_get_contents($url));
if (!$verify->success) { $error = "Invalid captcha"; }

// (C) SEND MAIL
if ($error=="") {
  $mailTo = "john@doe.com"; // ! CHANGE THIS TO YOUR OWN !
  $mailSubject = "Contact Form";
  $mailBody = "";
  foreach ($_POST as $k=>$v) { 
    if ($k!="g-recaptcha-response") { $mailBody .= "$k: $v\r\n"; }
  }
  if (!@mail($mailTo, $mailSubject, $mailBody)) { $error = "Failed to send mail"; }
}

This should not be much of a mystery… We are just sending the captcha and secret key to the reCaptcha server for validation. Thereafter, send the submitted contact form out via email.

 

 

USEFUL BITS & LINKS

Finally, here are a few extra bits and links that may be useful to you.

 

WHY NOT RECAPTCHA V3?

Please do take note that reCaptcha V3 works in a different manner. It is completely “silent”, no image challenge will be shown to the user, and the scripts will give you a score as to how likely the user is a bot. Sounds magical, but I personally don’t quite like the idea of it.

This very likely involves machine learning and data capturing. I.E. Data is captured on how the user interacts with your website. The score is then calculated based on a comparison against how other users usually interact with your website, and probably with other similar websites too. So, just nope. I rather stick with the “low tech” image challenge.

 

SECURITY STRENGTH

If you are still getting a lot of spambot messages after implementing the captcha, you can change the security level. Go back to the Google reCAPTCHA admin panel, turn the slider all the way to “most secure” under the advanced settings. Some users may get a more difficult captcha challenge, but it does filter out a lot of unwanted spam.

 

EXTRA) AJAX FORM SUBMISSION

EXTRA-AJAX.php
function doajax () {
  // (B1) GET FORM DATA
  var data = new FormData();
  data.append("name", document.getElementById("name").value);
  data.append("email", document.getElementById("email").value);
  data.append("message", document.getElementById("message").value);
  // REQUIRED: APPEND CAPTCHA RESPONSE
  data.append("g-recaptcha-response", grecaptcha.getResponse());
 
  // (B2) AJAX REQUEST
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "3-process.php");
  xhr.onload = function () {
    console.log(this.response);
  // DO SOMETHING AFTER FORM SUBMISSION
  };
  xhr.send(data);
  return false;
}

How about submitting the form via AJAX? Simply append g-recaptcha-response: grecaptcha.getResponse() to the data, and POST to the server as usual.

 

 

INFOGRAPHIC CHEAT SHEET

How To Create PHP Contact Form (click to enlarge)

 

USEFUL LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this short tutorial. I hope it will help you to fight off some nasty spam on your website, and if you have stuff you wish to add on to this guide, please feel free to comment below. Good luck and happy coding!

24 thoughts on “Simple PHP Contact Form With Google reCaptcha – Free Code Download”

  1. My form is currently being spammed with bots bypassing the captcha challenge using the Google speech to text api: =LINK REMOVED=

    Do you have a solution for that?

  2. Thanks Toh for the reply. I tried to modify but still not getting the results. I’m not an expert but I’m sure if you looked at it, you can easily fix the errors. Please help. Thanks!

    = CODE REMOVED =

    1. Went back to memory lane a little, not quite sure if this is what you want, set the “email from” to whatever the user enters in the contact form – mail($mailTo, $mailSubject, $mailBody, "From: " . $_POST['email']); Not recommended for security reasons though.

      Otherwise, can’t help fix your personal project any further… Try hiring a freelancer if still unsure, or seek help from other programming forums – Good luck.

      https://code-boxx.com/faq/#help
      https://code-boxx.com/set-mail-from-php/

  3. Hi, can you modify the code where the email address is displayed in the From header? When I receive the form submission, the emails in my inbox are not showing the sender’s name and email address. Thanks.

  4. Can you please explain.

    1) I have done -> STEP 1) REGISTER SITE AT GOOGLE RECAPTCHA
    2) I have done -> Insert the site key into 2-form.php and secret key into 3-process.php.
    3) I have done -> Change $mailTo to your own in 3-process.php.
    4) I have copied the code from 2-form.php onto my website page
    5) Now what? What do I do with the file 2-form.css???? Do I upload it somewhere using cPanel File Manager????
    6) What do I do with the file 3-process.php ??? Do I copy the copy the code onto the same page as 2-form.php OR do I upload the whole file 3-process.php with using cPanel File Manager???? — If so where????

  5. Thank you so much! Very nice form, and easy to implement.
    I’m using the non-ajax implementation and wonder why after submission the page reloads to the top? My “success message” is displayed, but since my form is at bottom of website a user would have to scroll all the way back down to see success message. Thank you.

      1. I also would like to know how to get rid of all the letters and characters that show up on the to of the incoming email before it shows the actual information that the person submitted like Name, Email, and Comments.

        I’m new to HTML and PHP so your response above doesn’t help me. What entire sequence needs to change? How to submit by AJAX? How do I use grecaptcha.getResponce() to stop all the garbage on top of the incoming email?

      2. I think I catch what you are trying to do. You want to remove the “g-recaptcha-response” field from the email –

        foreach ($_POST as $k=>$v) { if ($k!="g-recaptcha-response") { $mailBody .= "$k: $v\r\n"; }}

        Done, and nice drift. “I am new” is a perfect excuse when it comes to not reading a tutorial, nor studying 18 lines of PHP code. Think I will adopt that too. 😛 Good luck with your project!

      3. Thank you SO much! I really appreciate it. At first I didn’t know what to do with the code you gave but after a few attempts I seen in the SEND MAIL section a line of code that started the same and replaced it… it worked perfectly!

        After submitting the mailform, I was getting a blank page. After some searching I found this little bit of code that I added at the bottom of the PHP that redirected to a Thank You page. Now it all works great!

        //done. redirect to thank-you page.
        header(‘Location: thank_you.html’);
        exit;

  6. Hi, please, Ajax version is good. Email send ok, message bad language (utf-8?), confirmation of the sent message is OK, form data not CLEAR 🙁
    Can i ask for help?
    Sorry my bad english, thank you.

      1. Hi, I have problem: When I send a form and I get message, that the it was sent, the original message is not deleted. After sending Ajax should deletes message.

  7. In the ajax version, I have tried to add another field. But, it does not show up in the message that my mail recieves. It does not get the data.

Leave a Comment

Your email address will not be published. Required fields are marked *