How to PHP Contact Form with Google reCAPTCHA

How to PHP Contact Form with Google reCAPTCHA

How to PHP Contact Form with Google reCAPTCHA

0 Sales


A contact form is a vital component of every website. By entering the form, the visitor is able to interact with the site administrator. The contact request form is used for a variety of purposes, including submitting enquiries, recommendations, and requests. PHP makes it simple to add contact form features. In most cases, the contact request data is delivered to the administrator through email. PHP may be used to create a contact form with email capability.


The CAPTCHA function is quite important for protecting forms from bots. Make sure that the CAPTCHA validation is enabled on the contact form to prevent spam submissions. Google reCAPTCHA is by far the most successful approach for incorporating CAPTCHA into a contact form. This article will walk you through the process of creating a contact form and integrating Google reCAPTCHA with PHP.


Process of integrating a PHP contact form with Google reCAPTCHA:


- Create API keys for Google reCAPTCHA.

- To accept contact requests, create an HTML form.

- Insert a reCAPTCHA checkbox widget into your contact form.

- Use Google reCAPTCHA and PHP to validate form data.

- PHP is used to send form data via email.


Generate Google reCAPTCHA API keys


Before you begin using Google reCAPTCHA, you must first obtain the Site key and Secret key in order to utilise the reCAPTCHA API. Register your website in the Google reCAPTCHA Admin panel to receive a site and secret keys. You can follow a step-by-step procedure to generate the Google reCAPTCHA Site key and Secret key.


Create HTML Form with CAPTCHA


Build some HTML components that will receive user input. The HTML form below has several input fields (Name, Email, Subject, and Message) for submitting a contact request.


Add the following Google reCAPTCHA widget to your contact form:


- Include the JavaScript library for reCAPTCHA.

- To link a reCAPTCHA checkbox widget to a form, use the g-recaptcha tag element.

- In the data-sitekey element, provide the Site Key of the reCAPTCHA API.


<script src="https://www.google.com/recaptcha/api.js" async defer>script>

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

<form action="" method="post" class="cnt-form">
    <div class="form-input">
        <label for="name">Namelabel>
        <input type="text" name="name" placeholder="Enter your name" value="echo !empty($postData['name'])?$postData['name']:''?>" required="">
    <div class="form-input">
        <label for="email">Emaillabel>
        <input type="email" name="email" placeholder="Enter your email" value="echo !empty($postData['email'])?$postData['email']:''?>" required="">
    <div class="form-input">
        <label for="subject">Subjectlabel>
        <input type="text" name="subject" placeholder="Enter subject" value="echo !empty($postData['subject'])?$postData['subject']:''?>" required="">
    <div class="form-input">
        <label for="message">Messagelabel>
        <textarea name="message" placeholder="Type your message here" required="">echo !empty($postData['message'])?$postData['message']:''?>textarea>
    <div class="form-input">
        <div class="g-recaptcha" data-sitekey="echo $siteKey?>">div>
    <input type="submit" name="submit" class="btn" value="Submit">


After the contacting form data is sent to a server-side module (submit.php) for validation when the form is submitted. Also included the server-side attached document script at the start of the file, near the contact form.


// Include form submission script 
include_once 'submit.php'; 


Contact Form Submission with reCAPTCHA Verification (submit.php)



This submit.php file provides scripting that manages form registration and contact request processing.


- Using the PHP $_POST variable, get input data from form fields.

- Check to see that the input fields are not empty.

- Use the PHP FILTER VALIDATE EMAIL filter to validate email addresses.

- Use the g-recaptcha-response POST argument to validate the reCAPTCHA checkbox.

- Verify reCAPTCHA response using PHP — Use the secret and response parameters to call the Google reCAPTCHA API.

     - secret – Enter the Secret Key here.
     - response – Specify the user's response to g-recaptcha-response.

- If the reCAPTCHA API delivers a successful answer, the contact request will be considered genuine and will be processed further.

- Using the PHP mail() function, send contact form data to the admin through email.

- The user is presented the contact form submission status message.


// Google reCAPTCHA API key configuration 
$siteKey     'Insert_reCaptcha_Site_Key'; 
$secretKey     'Insert_reCaptcha_Secret_Key'; 
// Email configuration 
$toEmail '[email protected]'; 
$fromName 'Sender Name'; 
$formEmail '[email protected]'; 
$postData $statusMsg $valErr ''; 
$status 'error'; 
// If the form is submitted 
    // 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 
        $valErr .= 'Please enter your name.
    if(empty($email) || filter_var($emailFILTER_VALIDATE_EMAIL) === false){ 
        $valErr .= 'Please enter a valid email.
        $valErr .= 'Please enter subject.
        $valErr .= 'Please enter your message.
        // 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 
                // Send email notification to the site admin 
                $subject 'New contact request submitted'; 
                $htmlContent " 

Contact Request Details


Name: ".$name."


Email: ".$email."


Subject: ".$subject."


Message: ".$message."

                ";                                  // 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 '

Please fill all the mandatory fields:

);     } } // Display status message echo $statusMsg;




Using HTML and PHP, the above illustration script provides a solid contact form with CAPTCHA and mail capability. It aids with the integration of contact form functionality into a website while also protecting against bots and spam. The above PHP contact form script may be used on any blog, especially those with mobile responsive layouts.


You can use it for personal or commercial projects. You can't resell it partially or in this form.


Create Date : Jan 18, 2022

Updated Date : Jan 23, 2022


Comments : 0

Downloads : 0