Web Development & WordPress

Adding Google Recaptcha v3 to Contact Form (PHP/HTML): Spam issue fixed

So, client has a html site with contact form with a php mailer script, it was getting lots of spam comments. Client wanted to protected it from the spam using google Recaptcha v3. Here is the simple html and the related PHP Mailer with complete setup with google Recaptcha v3. Just you need to use your own SITE KEY and SECRET KEY to make it work.

Here is the basic HTML Contact Form, at the bottom of the code there is YOUR SITE KEY, please replace it with your google Recaptcha v3 Site Keys

<html>
<head>
</head>
<body>
<div id="wrapper">
<div id="content">
<div class=""><div class=""><div><div class="yodlecms_column yodlecms_col_right3 contact-col" style="width: 290px;">
<div class="contact-form">
<form name="contactform" id="contactform" method="post" action="send_email.php">
<input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
<table width="250px">
<tbody><tr>
<td valign="top">
<label for="first_name">First Name *</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top" "="">
<label for="last_name">Last Name *</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address *</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Telephone Number</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Comments *</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="button" value="Submit" onclick="submitContactForm()">
</td>
</tr>
</tbody></table>
</form></div>
</div>
</div>
<!-- reCAPTCHA v3 -->
<script src="https://www.google.com/recaptcha/api.js?render=YOUR SITE KEY"></script>
<script>
function submitContactForm() {
grecaptcha.ready(function() {
grecaptcha.execute("YOUR SITE KEY", {action: "contact"}).then(function(token) {
document.getElementById("g-recaptcha-response").value = token;
document.getElementById("contactform").submit();
});
});
}
</script>
</div></div></div></div></body></html>

Here is the send_email.php php script for the Contact Form which i shared above, in this PHP Script replace YOUR SECRET KEY , with your google Recaptcha v3 Secret Keys. Use your own / company Email address ( where you want to receive the email) in the place of YOUR EMAIL ADDRESS. Also change Email Subject as per your requirement.

Also, at the bottom of the code there is “From: Contact Form noreply@yoursite.com“, please use your site domain in place of “yoursite.com” otherwise hosting may block the mail.

<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "YOUR EMAIL ADDRESS";
$email_subject = "Email from YOUR Site";
// reCAPTCHA v3 Secret Key
$recaptcha_secret = "YOUR SECRET KEY";
function died($error) {
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// Verify reCAPTCHA v3
if(!isset($_POST['g-recaptcha-response']) || empty($_POST['g-recaptcha-response'])) {
died('reCAPTCHA verification failed. Please try again.');
}
$recaptcha_response = $_POST['g-recaptcha-response'];
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_data = array(
'secret' => $recaptcha_secret,
'response' => $recaptcha_response,
'remoteip' => $_SERVER['REMOTE_ADDR']
);
$recaptcha_options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($recaptcha_data)
)
);
$recaptcha_context = stream_context_create($recaptcha_options);
$recaptcha_result = file_get_contents($recaptcha_url, false, $recaptcha_context);
$recaptcha_json = json_decode($recaptcha_result, true);
if(!$recaptcha_json['success'] || $recaptcha_json['score'] < 0.5) {
died('reCAPTCHA verification failed. Please try again.');
}
// Validation
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_from = $_POST['email'];
$telephone = $_POST['telephone'];
$comments = $_POST['comments'];
$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 .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// From uses your domain to prevent cPanel from rejecting it
// Reply-To is set to visitor's email so you can reply directly to them
$headers = 'From: Contact Form <noreply@yoursite.com>' . "\r\n";
$headers .= 'Reply-To: ' . clean_string($email_from) . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
?>
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>

Leave a Reply