A contact form is an essential element for websites. It allows the visitor to communicate with the site admin by submitting the form. The contact request form is used for many purposes, like sending queries, suggestions, requests, etc. Contact form functionality can be implemented easily with PHP. Generally, the contact request data is sent to the admin via email. You can build a contact form with email functionality using PHP and implement a CAPTCHA or reCAPTCHA feature to prevent automated spam submissions.
The CAPTCHA feature is very useful to protect forms against bots. Make sure the CAPTCHA validation is added to the contact form to protect against spam submissions. Google reCAPTCHA is the most effective solution to integrate CAPTCHA in the contact form. This tutorial provides a simple example of creating a contact form using HTML and PHP with Google reCAPTCHA integration to prevent spam submissions. The form collects the user’s name, email, subject, and message, and sends the information to a specified admin email address upon submission. The form also includes validation for required fields and email format, as well as reCAPTCHA verification to ensure that the submission is made by a human user.
PHP contact form with Google reCAPTCHA integration process:
Before getting started with Google reCAPTCHA, the Site key and Secret key are required to use the reCAPTCHA API. Register your site on the Google reCAPTCHA Admin console and get a site and secret keys. You can follow the steps below to create Google reCAPTCHA API keys.
Steps to generate Google reCAPTCHA API keys:
Note: Make sure to use the correct keys for your environment (development or production).
The following code snippet shows how to create a contact form with Google reCAPTCHA integration using HTML.
Steps to create a contact form with reCAPTCHA widget:
Add Google reCAPTCHA widget to contact form:
g-recaptcha tag element to attach reCAPTCHA checkbox widget with form.data-sitekey attribute.<!-- Google recaptcha API library -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<!-- Display status message -->
<?php if ($errors): ?>
<div class="status-msg error">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo htmlspecialchars($error); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ($status): ?>
<div class="status-msg success"><?php echo htmlspecialchars($status); ?></div>
<?php endif; ?>
<form action="" method="post" class="cnt-form">
<!-- Form fields -->
<div class="form-input">
<label>Name</label>
<input
type="text"
name="name"
required
autocomplete="name"
placeholder="Your name"
value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>">
</div>
<div class="form-input">
<label>Email</label>
<input
type="email"
name="email"
required
autocomplete="email"
placeholder="ex: your@email.com"
value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
</div>
<div class="form-input">
<label>Subject</label>
<input
type="text"
name="subject"
required
placeholder="Subject of your request"
value="<?php echo htmlspecialchars($_POST['subject'] ?? ''); ?>">
</div>
<div class="form-input">
<label>Message</label>
<textarea
name="message"
required
placeholder="Type your message here"><?php echo htmlspecialchars($_POST['message'] ?? ''); ?></textarea>
</div>
<!-- Google reCAPTCHA box -->
<div class="form-input">
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY_HERE"></div>
</div>
<!-- Submit button -->
<input type="submit" name="submit" class="submit-btn" value="Submit">
</form>
The following code snippet shows how to handle the contact form submission with Google reCAPTCHA verification using PHP.
Steps to handle contact form submission with reCAPTCHA validation:
g-recaptcha-response POST parameter.secret – Specify Secret Key.response – Specify user’s response received from g-recaptcha-response.Note: Place this code at the top of the HTML form page.
<?php
$errors = [];
$status = '';
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
// Sanitize and validate input fields
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$recaptchaResponse = !empty($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : '';
// Validate form fields
if (empty($name)) {
$errors[] = "Please enter your name";
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Please enter a valid email address.";
}
if (empty($subject)) {
$errors[] = "Please enter a subject.";
}
if (empty($message)) {
$errors[] = "Please enter your message.";
}
// Verify Google reCAPTCHA
if (empty($recaptchaResponse)) {
$errors[] = "Please complete the reCAPTCHA.";
} else {
$recaptchaSecret = 'YOUR_SECRET_KEY_HERE'; // Replace with your reCAPTCHA secret key
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$recaptchaSecret}&response={$recaptchaResponse}");
$responseKeys = json_decode($response, true);
if (intval($responseKeys["success"]) !== 1) {
$errors[] = "Robot verification failed, please try again.";
}
}
// If no errors, send email
if (empty($errors)) {
$to = "admin@example.com"; // Replace with your admin email
$email_subject = "Contact Form: ".htmlspecialchars($subject);
// Email body content using HTML template
$email_body = '
<html>
<head>
<style>
body { font-family: Arial, sans-serif; background: #f9f9f9; }
.email-container { background: #fff; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px #eee; }
.header { font-size: 17px; color: #333; margin-bottom: 16px; }
.info { margin-bottom: 12px; }
.label { font-weight: bold; color: #555; }
.message { background: #f1f1f1; padding: 12px; border-radius: 4px; }
</style>
</head>
<body>
<div class="email-container">
<div class="header">New Contact Form Submission</div>
<div class="info"><span class="label">Name:</span> ' . htmlspecialchars($name) . '</div>
<div class="info"><span class="label">Email:</span> ' . htmlspecialchars($email) . '</div>
<div class="info"><span class="label">Subject:</span> ' . htmlspecialchars($subject) . '</div>
<div class="label">Message:</div>
<div class="message">' . nl2br(htmlspecialchars($message)) . '</div>
</div>
</body>
</html>';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: " . htmlspecialchars($name) . " <" . $email . ">\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
if (@mail($to, $email_subject, $email_body, $headers)) {
$status = "Thank you! Your message has been sent successfully.";
// Clear form fields
$_POST = [];
} else {
$errors[] = "There was an error sending your message. Please try again later.";
}
}
}
?>
Note: Replace YOUR_SITE_KEY_HERE and YOUR_SECRET_KEY_HERE with your actual Google reCAPTCHA site key and secret key respectively. Also, update the admin email address in the $to variable to receive contact form submissions.
You can use the PHP contact form with attachment script to send file attachment with the contact request email.
This example script builds a simple contact form with CAPTCHA and email functionality using HTML and PHP. It helps to integrate contact form functionality into a webpage and protect it from bots and spam. You can use this PHP contact form script on any website including a mobile responsive webpage layout. Make sure to test the form thoroughly to ensure it works as expected and handles errors gracefully.
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
I was wondering how I can integrate captcha with your article: Send Email with Attachment on Form Submission using PHP Why is that article not using captcha?
This works great, thank you. However on iOS 16 and iPad os 16, to doesn’t work… Anyone else having this issue?
Thanks! Really helpful!
*You have to get your reCaptcha V2, but still good!