Sunday, 8 December 2013

How to Create a Contact Form for Your Website in an Easy Way : A Set of Step by Step Tutorials Using HTML5, CSS3 and PHP (6)

(For the latest PDF files Merger Software please have a look at the top of the left margin, inside the red box.)
Continues From Part 5.

How to add reCaptch to the Contact Form to prevent spam and bots?

My next goal is adding a captcha to recognise spammer bots from human interacting individuals. First you need to get one. I used the free reCapatch from here. reCapatch gives you a pair of keys, one private key for the server-side inside the demoPoster.php, and one public key for the client-side inside your demoMain.php.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
        require_once('recaptchalib.php');
        $privatekey = "xxxxx-xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxx";
        $resp = recaptcha_check_answer ($privatekey,
                                    $_SERVER["REMOTE_ADDR"],
                                    $_POST["recaptcha_challenge_field"],
                                    $_POST["recaptcha_response_field"]);
        
        if (!$resp->is_valid) {
            // What happens when the CAPTCHA was entered incorrectly
            exit ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
             "(reCAPTCHA said: " . $resp->error . ")");
        }

Therefore your demoPoster.php file would be something like this.I moved lines (1) and (2) of the previous codes, respectively, to the lines (2) and (3) of following PHP file (download PHP code in Zip format here or open the code in text format here).

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
    require_once('recaptchalib.php');
    $privatekey = "xxxxx-xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxx";
    $Name = Trim(stripslashes($_POST['Name'])); 
    $City = Trim(stripslashes($_POST['City'])); 
    $Email = Trim(stripslashes($_POST['Email'])); 
    $Subject = Trim(stripslashes($_POST['Subject']));
    $Message = Trim(stripslashes($_POST['Message']));
    if ((empty($Name))||(empty($Email ))||(empty($Message))) {
                print "<meta http-equiv=\"refresh\" content=\"0;URL=demoError.html\">";
                exit();
    }
    else{
        list($emailPart, $domainPart) = explode('@', $Email);
        $one=filter_var($Email, FILTER_VALIDATE_EMAIL);
        $two=MailIPAddress($domainPart);
        if (!(($one) && ($two))) {
            print "<meta http-equiv=\"refresh\" content=\"0;URL=demoError.html\">";
            exit();
        }
        $resp = recaptcha_check_answer ($privatekey,
                                    $_SERVER["REMOTE_ADDR"],
                                    $_POST["recaptcha_challenge_field"],
                                    $_POST["recaptcha_response_field"]);
        
        if (!$resp->is_valid) {
            // What happens when the CAPTCHA was entered incorrectly
            exit("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
             "(reCAPTCHA said: " . $resp->error . ")");
        } 
        //Next send contact to website admin.
        $EmailToAdmin = "carlo.dj@messiahpsychoanalyst.org"; //Put your website admin email here. Don't forget quotes. 
        // body of the email your own admin receives
        $Body = "RE: Contact from visitors";
        $Body .= "\n";
        $Body .= "Name: ";
        $Body .= $Name;
        $Body .= "\n";
        $Body .= "City: ";
        $Body .= $City;
        $Body .= "\n";
        $Body .= "Subject: ";
        $Body .= $Subject;
        $Body .= "\n";
        $Body .= "Email: ";
        $Body .= $Email;
        $Body .= "\n";
        $Body .= "Message: ";
        $Body .= "\n";
        $Body .= $Message;
        $Body .= "\n";
        // send email to admin
        $posted = mail($EmailToAdmin, $Subject, $Body, "From: <$Email>");
        // redirect to thanks page 
        if ($posted){
            print "<meta http-equiv=\"refresh\" content=\"0;URL=demoThanks.php\">";
            //After thank you send an email containing his message to the visitor
            // prepare email body text
            $Body = " Madam/Sir,\n Thank you for your message.\n Dysprosium.\n";
            $Body .= " ======================================================\n\n";
            $Body .= "Name: ";
            $Body .= $Name;
            $Body .= ", Esq.";
            $Body .= "\n";
            $Body .= "From: ";
            $Body .= $City;
            $Body .= "\n";
            $Body .= "Email: ";
            $Body .= $Email;
            $Body .= "\n";
            $Body .= "Subject: ";
            $Body .= $Subject;
            $Body .= "\n";
            $Body .= "Message: ";
            $Body .= "\n";
            $Body .= $Message;
            $Body .= "\n";
            // send email 
            mail($Email, $Subject, $Body, "From: <$EmailToAdmin>");
        }
        else{
          //do nothing for now
        }
    }
?>
<?Php
/**
 * http://www.electrictoolbox.com/php-get-mail-server-ip-address/
 * Get a mail server's IP address with PHP
 * Posted November 9th, 2012 in PHP by Chris Hope
 * Returns an IP address that mail can be delivered to for the passed in domain.
 *
 **/
    function MailIPAddress($domain) {
        $ip = false;
        $records = dns_get_record($domain, DNS_MX);
        $priority = null;
        foreach ($records as $record) {
            if ($priority == null || $record['pri'] < $priority) {
                $myip = gethostbyname($record['target']);
                // if the value returned is the same, then the lookup failed
                if ($myip != $record['target']) {
                    $ip = $myip;
                    $priority = $record['pri'];
                }
            }
        }
        if (!$ip) {
            $ip = gethostbyname($domain);
            // if the value returned is the same, then the lookup failed
            if ($ip == $domain) {
                $ip = false;
            }
        }
        return $ip;
    }
?>

Inside line (28), instead of

exit("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
             "(reCAPTCHA said: " . $resp->error . ")");
 you can use a PHP print and redirect error response to a designed HTML page; similar to line (18).

Please insert the following snippet of client-side reCaptcha into the Contact Form page.

1
2
3
4
5
<?php
    require_once('recaptchalib.php');
    $publickey = "xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // you got this from the signup page
    echo recaptcha_get_html($publickey);
?>

Alternatively, you can use a JavaScript snippet, instead of PHP, for the reCaptcha.

<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"></script>

To be able to position and style the reCaptcha, you need to put that embraced in a division HTML div tag.

1
2
3
4
5
6
7
<div id="recaptcha_widget_div">
    <?php
        require_once('recaptchalib.php');
        $publickey = "xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // you got this from the signup page
        echo recaptcha_get_html($publickey);
    ?>
</div>

CSS codes for  the division goes at the top inside the style.

1
2
3
4
5
#recaptcha_widget_div {
    margin-top: 20px;
    margin-bottom: 10px;
    margin-left: 112px;
}

You need to add a JavaScript snippet provided by reCaptcha to select your favourite theme.

1
2
3
4
5
<script type= "text/javascript">
    var RecaptchaOptions = {
        theme: 'white'
    };
</script>

You have a choice of different themes, glass, white and so on that you can learn from reCaptch site and put in place of 'white' in above snippet . You have noticed one line

require_once('recaptchalib.php');

For that you need to take the recaptchlib.php from their website and upload it to the same directory as of your contact form in your web-server hosting. Then your contact form page should be something like the next snippet (download PHP code in Zip format here or open the code in text format here),

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
<!DOCTYPE html>
<!--
Created on 08-December-2013, 15:45:51.
Peter Jones codesforus.blogspot.com
Copyrights.
-->
<html>
    <head>
        <title> Dysprosium Contact Form</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <script type= "text/javascript">
            var RecaptchaOptions = {
                theme: 'white'
            };
        </script>
        <style>
            
            #contact-wrapper {
                margin: 20px auto;
                border: 2px solid #ccc;
                border-radius: 7px;
                padding: 20px 50px 20px 50px;
                background: transparent;
                width: 600px;
            }

            #contact-area {
                width: 600px;
                margin-top: 25px;
            }
            
            #contact-area label {
                float: left;
                margin-right: 15px;
                padding-top: 5px;
                width: 100px;
                text-align: right;
                font-size: 100%;
            }

            #contact-area input, #contact-area textarea {
                margin: 0px 0px 10px 0px;
                border: 2px solid #ccc;
                border-radius: 5px;
                padding: 5px;
                width: 471px;
                font-family: Helvetica, sans-serif;
                font-size: 110%;
            }

            #contact-area textarea {
                height: 90px;
            }

            #contact-area textarea:focus, #contact-area input:focus {
                border: 2px solid #900;
            }

            #contact-area input.submit-button {
                float: left;
                cursor: pointer; 
                margin-top:10px;
                margin-left:112px;
                background: transparent;
                width: 100px;
                font-size: 100%;
                color: #024d8e
            }

            #contact-area input[type="submit"]:hover{
                border: 2px solid #900;
            } 

            #recaptcha_widget_div {
                margin-top: 20px;
                margin-bottom: 10px;
                margin-left: 112px;
            }
      
        </style>
    </head>
    <body>
        <div id="contact-wrapper">
            <div id="contact-area">
                <form method="post" action="demoPoster.php">
                    <label for="Name"><span style="color: red; font-size: 100%">*&nbsp;</span>Name:</label>
                    <input type="text" name="Name" id="Name" value="" />
                    <label for="City">City:</label>
                    <input type="text" name="City" id="City" value="" />
                    <label for="Email"><span style="color: red; font-size: 100%">*&nbsp;</span>Email:</label>
                    <input type="text" name="Email" id="Email" value="" />
                    <label for="Subject">Subject:</label>
                    <input type="text" name="Subject" id="Subject" value="" />
                    <label for="Message"><span style="color: red; font-size: 100%">*&nbsp;</span>Message:</label>
                    <textarea name="Message" rows="20" cols="20" id="Message"></textarea>
                    <p style="margin:20px auto 10px 112px;">Fields shown by <span style="color: red; font-size: 100%">*&nbsp;</span> are required.</p>
                        <div id="recaptcha_widget_div">
                            <?php
                                require_once('recaptchalib.php');
                                $publickey = "xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // you got this from the signup page
                                echo recaptcha_get_html($publickey);
                            ?>
                        </div>
                    <input type="submit" name="submit" value="Submit" class="submit-button" />
                </form>
                <div style="clear: both;">
                </div>
            </div>
        </div>
    </body>
</html>

Division at lines (107)  (108) has been added to give the flow to contact form after inserting the reCaptcha.
That is now a very simple robust contact form and can be used. Please have look at it here. I put its snapshot here.
Next we are going to give it final cosmetics touches and consolidate all scattered pages in one PHP page. Please click here.

Download this tutorial as PDF format here
Download part 1 to part 6 as PDF format here

No comments:

Post a Comment