PHP Contact Form with Google reCAPTCHA

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:

  • Generate Google reCAPTCHA API keys.
  • Create an HTML form to accept contact requests.
  • Add reCAPTCHA checkbox widget to contact form.
  • Validate form data with Google reCAPTCHA and PHP.
  • Send form data via email using PHP.

Generate Google reCAPTCHA API keys

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:

  1. Go to the Google reCAPTCHA Admin console.
  2. Click on the “Admin Console” button at the top right corner.
  3. Log in with your Google account.
  4. Fill in the required details:
    • Label: Enter a name for your reCAPTCHA (e.g., “My Website reCAPTCHA”).
    • reCAPTCHA type: Select “reCAPTCHA v2” and choose “I’m not a robot Checkbox”.
    • Domains: Enter your website domain (e.g., example.com).
    • Email: Enter your email address for notifications.
    • Accept Terms of Service: Check the box to accept the terms.
  5. Click on the “Submit” button.
  6. You will be redirected to a page displaying your Site key and Secret key. Copy these keys and keep them safe for later use.

Note: Make sure to use the correct keys for your environment (development or production).

Create HTML Form with CAPTCHA

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:

  • Define some HTML input elements to accept the user’s input (Name, Email, Subject, and Message).
  • At the top of the contact form, display the validation error and form submission status messages with PHP.

Add Google reCAPTCHA widget to contact form:

  • Include the reCAPTCHA JavaScript library.
  • Add g-recaptcha tag element to attach reCAPTCHA checkbox widget with form.
  • Specify Site Key of reCAPTCHA API in the 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>

Contact Form Submission with reCAPTCHA Verification

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:

  • Retrieve input data from the form fields using PHP $_POST variable.
  • Check whether the input fields are filled and not empty.
  • Validate email address with PHP FILTER_VALIDATE_EMAIL filter.
  • Validate reCAPTCHA checkbox with g-recaptcha-response POST parameter.
  • Verify reCAPTCHA response with PHP – Call the Google reCAPTCHA API with secret and response parameters.
    • secret – Specify Secret Key.
    • response – Specify user’s response received from g-recaptcha-response.
  • If reCAPTCHA API returns a success response, the contact request will be treated as valid and proceed further.
  • Send contact form data to the admin via email using the PHP mail() function.
  • The contact form submission status message is shown to the user.

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($emailFILTER_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($responsetrue);
        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.

Conclusion

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

3 Comments

  1. Bouke Said...
  2. Phil Said...
  3. Juan Carlos Aguirre Said...

Leave a reply

construction Need this implemented in your project? Request Implementation Help → keyboard_double_arrow_up