Welcome to a 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 are worried about spam? Well, let us walk through the steps to create a PHP contact form, and add Google reCaptcha to secure it – Read on!
TLDR – QUICK SLIDES
Fullscreen Mode – Click Here
TABLE OF CONTENTS
PHP CONTACT FORM
All right, let us now get started with the PHP contact form.
STEP 1) REGISTER AT GOOGLE RECAPTCHA
1A) ADD YOUR SITES
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.
1B) GET THE KEYS
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) HTML CONTACT FORM
<!-- (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 "<div id='notify'>$status</div>";
}
?>
<!-- (C) CONTACT FORM -->
<form id="cform" method="post">
<label>Name</label>
<input type="text" name="name" required>
<label>Email</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.
- Load the reCaptcha Javascript library.
- This part will run only when the contact form is submitted. Using
3-process.php
to verify the captcha, and send the contact form via email. - Self-explanatory. The contact form itself.
- 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
<?php
// (A) PROCESS STATUS
$status = "";
// (B) VERIFY CAPTCHA
$secret = "SECRET KEY"; // CHANGE 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) { $status = "Invalid captcha"; }
// (C) SEND MAIL
if ($status=="") {
$mailTo = "admin@site.com"; // CHANGE 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)) { $status = "OK"; }
else { $status = "Failed to send mail"; }
}
echo $status;
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.
EXTRA) AJAX FORM SUBMISSION
// (B1) GET FORM DATA - APPEND RECAPTCHA RESPONSE
var data = new FormData(document.getElementById("cform"));
data.append("g-recaptcha-response", grecaptcha.getResponse());
// (B2) AJAX FETCH
fetch("3-process.php", { method: "POST", body: data })
.then(res => res.text())
.then(txt => {
// DO SOMETHING AFTER FORM SUBMISSION
console.log(txt);
});
How about submitting the form via AJAX? Simply append g-recaptcha-response: grecaptcha.getResponse()
to the data, and POST to the server as usual.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a "paid scripts and courses" business, so every little bit of support helps.
Buy Me A Meal Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
Finally, here are a few extra bits and links that may be useful to you.
WHY NOT RECAPTCHA V3?
Please 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, and 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.
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET

LINKS & REFERENCES
- Google reCAPTCHA home page
- Official Google reCAPTCHA developer’s guide
- PHP PDO
- PHP Mail
- Mail not sending out? Here’s how to fix it – Code Boxx
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 to this guide, please feel free to comment below. Good luck and happy coding!
Hi, what Can I do to get allert about success or failed using ajax one code?
https://code-boxx.com/simple-ajax-php/
Is it possible to have the form send the user to a thank-you page after successfully filling out the form?
Yes, just do a redirect in PHP –
header("Location: http://site.com/thankyou.php");
How can this form be Centered?
margin: 0 auto
https://www.freecodecamp.org/news/how-to-center-anything-with-css-align-a-div-text-and-more/
https://blog.hubspot.com/website/center-div-css
Very easy to install this form, only 5 minutes, works perfect!
On computer form good, but on mobile too small. Ho to resize form on mobile?
Google did not provide a way to resize the reCaptcha, but we can apply CSS scale on it –
@media screen and (max-height: 767px) { .g-recaptcha { transform:scale(1.2); }}
Does this 3-process.php code example follow the PHP 8.1 version rules?
Thanks,
Jim
Which “rule” in particular? https://www.php.net/releases/8.1/en.php
Doesn’t work with Safari. The browser console gives this message: “The source list for Content Security Policy directive ‘script-src’ contains an invalid source: ”strict-dynamic”. It will be ignored.”
A Google search turns up lots and lots of people complaining about this message when using Safari and ReCAPTCHA, but no solutions.
Report this to Google and Apple… I cannot fix Safari and the ReCAPTCHA API. But chances are, they will continue to point fingers at each other and refuse a fix. 😆
Hi It does work, thank you so much, but is there a way I can change the mail from field as I have a very oddly named server?
Just do a search for “change PHP mail from”.
https://code-boxx.com/faq/#help “Answers can be found all over the Internet.”
Under // (C) SEND MAIL
add this:
$headers = “From: noreply@yourdomain.com“;
I followed your instructions but I get a invalid captcha message. I have checked the input for site key and secret key are correct. I actually recreated them several times to be sure.
Any clues?
No idea. Can be anything. Turn on your error reporting and var_dump($verify) to see what Google reCaptcha is complaining about.
https://code-boxx.com/faq/#notwork “Not working”
https://code-boxx.com/faq/#help “Unclear question – Any Idea?”.
I had the same issue, and it was my server blocking the outgoing connection to Google. I added 142.250.187.228/32 to my outbound rules, and all working.
HI W.S. TOH , Thank you! for your code and video, works fine!!
Osvaldo