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.

The CAPTCHA feature is very useful to protect form against bots. Make sure the CAPTCHA validation is added to the contact form for protecting spam submission. Google reCAPTCHA is the most effective solution to integrate CAPTCHA in the contact form. This tutorial will show you how to create a contact form and integrate Google reCAPTCHA with PHP.

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 is required to use reCAPTCHA API. Register your site on the Google reCAPTCHA Admin console and get a site and secret keys. You can go through a step-by-step process to create Google reCAPTCHA Site key and Secret key.

Create HTML Form with CAPTCHA

Define some HTML elements to accept the user’s input. The following HTML form contains some input fields (Name, Email, Subject, and Message) to submit contact request.

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>

<!-- Status message -->
<?php if(!empty($statusMsg)){ ?>
    <div class="status-msg <?php echo $status?>"><?php echo $statusMsg?></div>
<?php ?>

<!-- Contact form fields -->
<form action="" method="post" class="cnt-form">
    <div class="form-input">
        <label for="name">Name</label>
        <input type="text" name="name" placeholder="Enter your name" value="<?php echo !empty($postData['name'])?$postData['name']:''?>" required="">
    </div>
    <div class="form-input">
        <label for="email">Email</label>
        <input type="email" name="email" placeholder="Enter your email" value="<?php echo !empty($postData['email'])?$postData['email']:''?>" required="">
    </div>
    <div class="form-input">
        <label for="subject">Subject</label>
        <input type="text" name="subject" placeholder="Enter subject" value="<?php echo !empty($postData['subject'])?$postData['subject']:''?>" required="">
    </div>
    <div class="form-input">
        <label for="message">Message</label>
        <textarea name="message" placeholder="Type your message here" required=""><?php echo !empty($postData['message'])?$postData['message']:''?></textarea>
    </div>
    <div class="form-input">
        <!-- Google reCAPTCHA box -->
        <div class="g-recaptcha" data-sitekey="<?php echo $siteKey?>"></div>
    </div>
    <input type="submit" name="submit" class="btn" value="Submit">
</form>

After the form submission, the contact request data is posted to a server-side script (submit.php) for processing. Include the server-side form submission script at the top of file where contact form is placed.

<?php 
// Include form submission script
include_once 'submit.php';
?>

Contact Form Submission with reCAPTCHA Verification (submit.php)

This submit.php file contains server-side code that handles form submission and process the contact request.

  • 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.
<?php 
// Google reCAPTCHA API key configuration
$siteKey     'Insert_reCaptcha_Site_Key';
$secretKey     'Insert_reCaptcha_Secret_Key';

// Email configuration
$toEmail 'admin@example.com';
$fromName 'Sender Name';
$formEmail 'sender@example.com';

$postData $statusMsg $valErr '';
$status 'error';

// If the form is submitted
if(isset($_POST['submit'])){
    
// Get the submitted form data
    
$postData $_POST;
    
$name trim($_POST['name']);
    
$email trim($_POST['email']);
    
$subject trim($_POST['subject']);
    
$message trim($_POST['message']);
    
    
// Validate form fields
    
if(empty($name)){
        
$valErr .= 'Please enter your name.<br/>';
    }
    if(empty(
$email) || filter_var($emailFILTER_VALIDATE_EMAIL) === false){
        
$valErr .= 'Please enter a valid email.<br/>';
    }
    if(empty(
$subject)){
        
$valErr .= 'Please enter subject.<br/>';
    }
    if(empty(
$message)){
        
$valErr .= 'Please enter your message.<br/>';
    }
    
    if(empty(
$valErr)){
        
        
// Validate reCAPTCHA box
        
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){

            
// Verify the reCAPTCHA response
            
$verifyResponse file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
            
            
// Decode json data
            
$responseData json_decode($verifyResponse);
            
            
// If reCAPTCHA response is valid
            
if($responseData->success){

                
// Send email notification to the site admin
                
$subject 'New contact request submitted';
                
$htmlContent "
                    <h2>Contact Request Details</h2>
                    <p><b>Name: </b>"
.$name."</p>
                    <p><b>Email: </b>"
.$email."</p>
                    <p><b>Subject: </b>"
.$subject."</p>
                    <p><b>Message: </b>"
.$message."</p>
                "
;
                
                
// Always set content-type when sending HTML email
                
$headers "MIME-Version: 1.0" "\r\n";
                
$headers .= "Content-type:text/html;charset=UTF-8" "\r\n";
                
// More headers
                
$headers .= 'From:'.$fromName.' <'.$formEmail.'>' "\r\n";
                
                
// Send email
                
@mail($toEmail$subject$htmlContent$headers);
                
                
$status 'success';
                
$statusMsg 'Thank you! Your contact request has submitted successfully, we will get back to you soon.';
                
$postData '';
            }else{
                
$statusMsg 'Robot verification failed, please try again.';
            }
        }else{
            
$statusMsg 'Please check on the reCAPTCHA box.';
        }
    }else{
        
$statusMsg '<p>Please fill all the mandatory fields:</p>'.trim($valErr'<br/>');
    }
}

// Display status message
echo $statusMsg;

Send Email with Attachment on Form Submission using PHP

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 to webpage and protect from bots and spam. You can use this PHP contact form script on any website including a mobile responsive webpage layout.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

3 Comments

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

Leave a reply

keyboard_double_arrow_up