PHP contact form with Google reCaptcha

Aneh Thakur

Aneh Thakur

. 2 min read

A contact form is a web-based form on a website that is used by the user to contact the site owner. Contact form provides a convenient way for users to ask questions. Users can fill the form and submit it. Generally, every website needs a contact form, so users can easily communicate with you, and know your products and services. Contact form is necessary for every website, no matter what website you are creating. Contact form helps users who are residing on your website and are phasing out some problems. The contact form can help visitors to share tips they are facing while using your website.

In this article, we will tell you how to create a fully working contact form in PHP with Google ReCaptcha. First, we need to create a User form so let’s get started.

Contact form with PHP

For this post, I am using Bootstrap to design my contact form. With the help of bootstrap we can create a responsive contact form it will save our time you can also create your custom design using custom CSS.

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>PHP contact form with Google captcha and email - example</title>
    <meta content="No matter what type of website you own or manage, you probably need a contact form which help your visitor to contact you for any related query." name="description" />
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
    <div class="container">
        <h1>PHP Contact form with Google Captcha</h1>
        <div>
            <form method="post" action="contact.php">
                <div class="mb-3">
                    <label for="name" class="form-label">Name</label>
                    <input type="text" class="form-control" id="name" name="name" placeholder="Your Complete Name">
                </div>
                <div class="mb-3">
                    <label for="exampleFormControlInput1" class="form-label">Email</label>
                    <input type="email" class="form-control" id="exampleFormControlInput1" name="email" placeholder="[email protected]">
                </div>
                <div class="mb-3">
                    <label for="exampleFormControlTextarea1" class="form-label">Query</label>
                    <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="query"></textarea>
                </div>
                <!-- Google ReCaptcha Block -->
                <div>
                    <div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjhRjyoMguw66mNSBgdpBF398AG"></div>
                </div>
                <div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
</body>
</html>

You can also add validation to this form using jQuery or Javascript. In the above code, you also find that I add the Google Recaptcha block you can read this post to know how to create the Google reCaptcha key.


Handel PHP contact form data

The design of the contact form is ready now we can handle data passed from the contact form.

<?php
if($_POST) {
    $name = "";
    $email = "";
    $query = "";

    $cap = $_POST['g-recaptcha-response'];
    $ch = curl_init('https://www.google.com/recaptcha/api/siteverify?secret=<My_RECAPTCHA_SECRET>&response='.$cap);                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");                                                                                                                               
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    $result = curl_exec($ch);
    curl_close($ch);

    $cap_response = json_decode($result);

    if($cap_response->success){

        $email_body = "<div>";
      
        if(isset($_POST['name'])) {
            $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
            $email_body .= "<div>
                               <label><b>Name:</b></label>&nbsp;<span>".$name."</span>
                            </div>";
        }
     
        if(isset($_POST['email'])) {
            $email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['email']);
            $email = filter_var($email, FILTER_VALIDATE_EMAIL);
            $email_body .= "<div>
                               <label><b>Visitor Email:</b></label>&nbsp;<span>".$visitor_email."</span>
                            </div>";
        }
          
        if(isset($_POST['query'])) {
            $query = filter_var($_POST['query'], FILTER_SANITIZE_STRING);
            $email_body .= "<div>
                               <label><b>Query:</b></label>&nbsp;<span>".$query."</span>
                            </div>";
        }
          
        $recipient = "[email protected]";
          
        $email_body .= "</div>";
    
        $email_title = "Query from Website";
     
        $headers  = 'MIME-Version: 1.0' . "\r\n"
        .'Content-type: text/html; charset=utf-8' . "\r\n"
        .'From: ' . $email . "\r\n";
          
        if(mail($recipient, $email_title, $email_body, $headers)) {
            echo "<p>Thank you for contacting us, $name. You will get a reply within 1 hours.</p>";
        } else {
            echo '<p>We are sorry but the email did not go through.</p>';
        }
    }else{
        echo '<p>Error validating captcha.</p>';
    }
    
    
      
} else {
    echo '<p>Something went wrong</p>';
}
?>

Now in the above code first we can get the data you can see in our contact form we use the method to post to send data to the server so to receive data we can use $_POST to receive data. Now before processing data, we can first verify that data sent from the client is sent by humans using Google reCaptcha verification you need to add your Google reCaptcha server key to verify. Once the user is verified we send mail to the user using the PHP mail method. That’s it.


Originally posted:- https://trinitytuts.com/php-contact-form-with-google-recaptcha/