Add Google reCaptcha to PHP Contact Form


0

In this tutorial we will discuss google recaptcha to php contact form

A contact form is a basic element for websites. It allows the user to contact with the website admin by submitting the form. The contact form request form is used for many reason, like sending queries, requests,suggestions etc. Contact form, function can be applied easily with PHP. Usually, the contact request data is sent to the admin by email.

The Form CAPTCHA attributes is very helpful to protect a form against bots form submit. Make sure the CAPTCHA validation is adding to the contact form for protected spam submission. Google reCAPTCHA is the most efficient solution to integrate CAPTCHA in the PHP contact form. In This articel will discuss you how to Add GooglereCaptcha to PHP Contact Form.

PHP contact form with Google reCAPTCHA embedding process:

Generate Google reCAPTCHA API keys.

  • Build an HTML form which accept contact requests.
  • Put reCAPTCHA checkbox feature to contact form.
  • Validate form data with Google reCAPTCHA with PHP.
  • Send form data by email in PHP.


Create Google reCAPTCHA API keys


Earlier getting started with Google reCAPTCHA, the Secret key and Site key is must required to use Google reCAPTCHA API. Register your website with url on the Google reCAPTCHA Admin console and get secret keys for your website. You can go over a step-by-step process to build Google reCAPTCHA Secret key and Site key.

Build HTML Form with CAPTCHA


Determine some HTML elements to accept the website user input information. The given HTML form store some input fields (Name, Email, Subject, and Message) to submit contact request.

Put Google reCAPTCHA widget to PHP contact form:

  • Add the reCAPTCHA JavaScript library.
  • Put g-recaptcha tag element to attach reCAPTCHA checkbox widget with PHP form.
  • Define 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>

When you form submit, the contact form request user data is sent to a server-side script (submit.php) for processing. Contain the server-side contact form submit php script at the uper file where contact form is located.

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

Contact Form Submission with Google reCAPTCHA Verification (submit.php)


Send contact data to the admin/anyuser by email using the PHP mail() function.
The contact form submission status message is indicate to the user.

  • Fetch input user data from the form fields using PHP $_POST variable.
  • Check whatever the input fields are filled and should not empty.
  • Validate email with PHP FILTER_VALIDATE_EMAIL filter.
  • Validate Google reCAPTCHA checkbox with g-recaptcha-response POST parameter.
  • Verify Google reCAPTCHA response using PHP – Call the reCAPTCHA API with secret key and action parameters.
  • secret – Specify Secret Key.
  • response – Specify user’s response obtained from g-recaptcha-response.
  • If Google reCAPTCHA API returns a success response, the contact form request will be addressed as valid and proceed more.
  • This submit.php file store server-side code which managed form submission and process the contact form request.
<?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($email, FILTER_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;

Also Read: How to download Image from the URL in PHP


Like it? Share with your friends!

0
Developer

0 Comments