Tek Eye Logo

Tek Eye

Contact Form for HTML and PHP

Apparently, user engagement is a good thing for a website's ranking, i.e. to help with Search Engine Optimisation (SEO). This article provides a tutorial for a simple website contact form that can be added to the bottom of a web page. The free browser JavaScript and web server PHP code can be copied and added to your website for a simple website feedback solution. This tutorial combines the code from several other Tek Eye articles to produce the final HTML form submission solution. If you are not interested in the details, jump to the final code towards the bottom of the article.

PHP Logo

Instead of a simple website contact form a full-blown commenting system could be used, such as Disqus or the Facebook Comments plugin. However, the integration and management of a commenting system can be painful, and free versions can carry bloated clickbait advertising. Even paid for commenting systems need constant attention. Aother option is choosing to roll your own commenting system, but you will be dealing with high levels of spam, trolling and misuse. Any form of website commenting support can be a headache.

Providing a form for a visitor to fill in is a longstanding and simple solution to providing engagement with website visitors. The form is provided for them to send in a message. A simple box is used to ask a question, or provide a comment. However, a good anti-spam measure is needed, for example CAPTCHA.

CAPTCHA is from "Completely Automated Public Turing test to tell Computers and Humans Apart". CAPTCHA is a test to see if a human or a bot (robot software) is visiting a website. CAPTCHA implementations include Google's reCAPTCHA, and Intuition Machines has hCAPTCHA, which is used to help identify objects and can generate some revenue for your website.

In this tutorial a simple HTML form for a message, supported by PHP code on the web server, is used for user engagement. Each time the form is filled in and submitted it generates an email to the person tasked with handling website visitor queries and contact. Email is easy to filter and mark as spam, plus the use of reCAPTCHA will reduce the worse of the spamming.

HTML Form Data

What is Needed for the Simple Website Messaging Form?

This simple website user engagement form requires a HTML page (web page) with a form and CAPTCHA support (reCAPTCHA is used here), and the website's web hosting server supporting PHP and email, which most do.

The contact web page has a HTML form with two boxes, one for a name for the person sending the message, and one for the message itself, and a send button. The boxes are filled in by the website visitor who then clicks a send button. A HTTP POST action occurs to send the data from the two boxes to a PHP script on the web server. Assuming the data is valid, and the reCAPTCHA response is correct, the PHP on the webserver puts the text from the two boxes into an email. The email is sent to the person tasked with dealing with the comments. Then the comments, all being well, can be added to the web page to which they are associated. In summary, the HTML contact form needs the following:

  1. Webserver support for sending an email from PHP.
  2. A HTML page with a HTML form that has name and message boxes and a send button.
  3. Support for reCAPTCHA to prevent abuse of the messaging system.
  4. A PHP script to process the HTML form's name field and message contents to generate and send an email.

1. Checking Webserver Support for PHP Email

If your website hosting supports PHP it probably supports email generation using PHP's mail function. For more information see the Tek Eye article PHP Mail Script for Testing Email Sending.

2. HTML Page with a Simple Form Sending Data to the Web Server

A simple feeback form is defined in HTML. When the send button on the form is pressed the data is sent to a PHP script on the web server. The PHP script processes the data. An example of a simple HTML form sending data to the web server is shown above. The process is descibed in this diagram:

HTML Form Processing

The full article on adding a PHP web server script to process the HTML form is in the Tek Eye article Simple HTML Contact Form for PHP Based Website.

3. Protecting the Form with reCAPTCHA

With a basic submission form working, the next step is to add reCAPTCHA code. A Google account is required to use reCAPTCHA. Visit the reCAPTCHA registration site and register a new website to use reCAPTCHA. One domain (e.g. example.com) and any of its sub-domains (e.g. subsite.example.com) is one website for registration purposes. Each registration provides a site key and a secret key to use in the reCAPTCHA implementation.

The reCAPTCHA process is based on Google's analysis of vistors to a website. A token is passed from the visitor's browser to the reCAPTCHA server via your website's server. A webpage score is returned that is used to determine if the webpage was accessed by a legitimate visitor or an automated process:

How does reCAPTCHA work

The full article on adding reCAPTCHA to a website is shown in the Tek Eye article reCAPTCHA Code to Download for Demo and Test.

4. Processing the Form Data on the Web Server and Sending an Email

Once the web form is submitted, and the reCAPTCHA score for the submission is correct. Then the data can be processed and used to send an email. The process begins with data sanitization, making sure the data is suitbale for processing by the web server. The Tek Eye article PHP Sanitize POST Data, Clean Up Input shows how to sanitize submitted data.

All the elements for showing a feedback or contact form, verifying it is correct and sending an email are now present. The final demo solution is a single web page with a HTML form, and a single PGP server script for processing the submission and building and sending out the email. It includes adding a HTML link in the form submission response for the website visitor to return to the web page they were reading.

The Final Code for a Website Contact or Feedback Form

Combining all the steps above produces this final code. It can be adapted to other types of forms on a web site.

Firstly, the initial HTML web page with the submission form. The script tags and the code between to the body tags can be added to other web pages to add the feedback form functionality to other web pages. Change YOUR_reCAPTCHA_SITE_KEY_GOES_HERE to your registered website's reCAPTCHA site key, and handle-form.php to the name of the file, and path if required, where you saved the PHP script on the server:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML Form Demo</title>      
        <script src="https://www.google.com/recaptcha/api.js" defer></script>
        <script>
            function submitForm() {
                document.getElementById("comment-form").submit();
            }
        </script>
    </head>
    <body>
        <h1>Send a comment or question...</h1>
        <form action="handle-form.php" method="post" id="comment-form">
            <div>
                <label style="width: 60px; display: inline-block;">Name:</label>
                <input type="text" name="name" maxlength="50" required="">
            </div>
            <div style="margin-top:1em;">
                <label style="width: 60px;">Message:</label>
                <textarea style="vertical-align: top;" name="message"
                          cols="70" rows="4"
                          maxlength="1000" required=""></textarea>
            </div>
            <input type="submit" value="Send" class="g-recaptcha"
                data-sitekey="YOUR_reCAPTCHA_SITE_KEY_GOES_HERE" data-callback="submitForm">
        </form>
    </body>
</html>

Now the web server code. Make the following changes to the example code provided:

  • Replace YOUR_reCAPTCHA_SECRET_KEY_GOES_HERE with the secret key for your website (the secret key, NOT the site key).
  • Add the appropriate email addresses for the email sending.
  • Change the domain for the link back check code to your website's domain.
  • If you get too much email spam change the reCAPTCHA response score from 0.5 to a higher value (0.6 to 1.0).

Here is the PHP web server script used in this example:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML Form Demo</title>
    </head>
    <body>
        <p>Processing feedback...</p>
        <?php 
            //Set an error message
            $submission_error = "Sorry, a submission error occurred: ";
            // Define a filter function for data sanitization
            function clean_data($data) {
                // trim whitespace
                $data = trim($data);
                // reduce website manipulation via HTML tags
                $data = htmlspecialchars($data);
                return $data;
            }
            //Check for reCAPTCHA token
            if (isset($_POST['g-recaptcha-response'])) {
                $captcha = $_POST['g-recaptcha-response'];
            } else {
                $captcha = false;
            }
            //If no reCAPTCA token, show an error, otherwise verify data.
            if (!$captcha) {
                //Do something with no reCAPTCHA available
                 echo "<p>".$submission_error." No verification data.</p>";
            } else {
                $secret='YOUR_reCAPTCHA_SECRET_KEY_GOES_HERE';
                $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".
                    $secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
                // Use json_decode to extract json response
                $response = json_decode($response);
                //See if verification failed
                if ($response->success===false) {
                    //Do something with failure
                    echo "<p>".$submission_error." Data verification failed.</p>";
                } else {
                    //If the reCAPTCHA is valid use the data
                    //Otherwise filter out bad submissions
                    //Change acceptable score as required
                    if ($response->score <= 0.5) {
                        //Do something to deny access
                        echo "<p>".$submission_error." Data check failed.</p>";
                    } else {
                        if(isset($_POST['message'])) {
                            //Sanitize the message
                            $message=clean_data($_POST['message']);
                            //Add the senders name
                            if(isset($_POST['name'])) {
                                $name=clean_data($_POST['name']);
                                $message="From: ".$name."\r\n".$message;
                            }
                            //Add the source web page
                            if(isset($_POST['referer'])) {
                                $message="Regards:".clean_data($_POST['referer'])."\r\n".$message;
                            }
                            //Set person to send the message to
                            $to='admin@example.com';
                            //Use an appropriate email subject
                            $subject='Website feedback';
                            //Wordwrap long content
                            $message=wordwrap($message, 70, "\r\n");
                            $headers='From: webmaster@example.com';
                            //Send the email
                            if(mail($to, $subject, $message, $headers))
                            {
                                echo "<p>Thank you ".$name.".<br\>".
                                    " Your feedback is welcome.</p>";
                            }
                            else 
                            {
                                echo "<p>".$submission_error." Failed to send feedback.</p>";
                            }
                        } else {
                            echo "<p>".$submission_error." No message to submit.</p>";
                        }
                    }
                }
            }
            //Back link to source page
            if(isset($_POST['referer'])) {
                $domain='example.com';
                $referer_domain=parse_url($_POST['referer'],PHP_URL_HOST);
                if($referer_domain==$domain)
                    echo '<a href="'.$_POST['referer'].'">Please click here to return to the previous page.</a>';
            }
        ?>
     </body>
</html>

Here is the HTML form submission in action:

HTML Form with reCAPTCHA

This is the generated email:

Email from HTML Form

See Also

Author:  Published:  

ShareSubmit to TwitterSubmit to FacebookSubmit to LinkedInSubmit to redditPrint Page

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

markdown CMS Small Logo Icon ↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.


Articles on:

Android Programming and Android Practice Projects, HTML, VPS, Computing, IT, Computer History, ↓markdown↓ CMS, C# Programming, Using Windows for Programming


Free Android Projects and Samples:

Android Examples, Android List Examples, Android UI Examples



Tek Eye Published Projects