Tuesday, 12 August 2014

RECAPTCHA CONTACT FORM

 RECAPTCHA CONTACT FORM




Once you've filled out the form, hit the Send! button. If you submitted the form by typing both of the words incorrectly, you will see an error page asking you fill out the form again. If you typed the words correctly, submitting the form will show you a confirmation page indicating the feedback was sent. This is all pretty simple behavior.
Now that you have an idea of what you will be creating, the subsequent sections will turn that idea into working PHP and HTML.

Creating a reCAPTCHA Account

The first thing to do before you write any code is to create a free reCAPTCHA account on Google's site. Go totheir site, and once you are there, you will see a gigantic Sign up Now! button that you can click:




Once you sign up, you'll need to activate the account on the domain you wish to use it:



For me, the domain is www.kirupa.com. Make sure to change this value for the domain your contact form will be living on. If this value doesn't match the domain your contact form is being used or tested from, the reCAPTCHA validation will not work.
After you have specified the domain, click on Create Key. After a few micromoments, you'll see a summary page that lists details about the key that you just created:



There are two pieces of information here that you need to know about for implementing the reCAPTCHA service on your site - the Public Key and Private Key. These two values are important, and you will need them in your code later on. Keep this summary page open so that you have easy access to them for later. Of course, you can always revisit the reCAPTCHA site and see these values, so don't panic if you accidentally close this page later.
Ok, now that you have your reCAPTCHA account setup for your domain, it's time to get to the fun stuff.

Displaying the reCAPTCHA Box

The next step is to show the reCAPTCHA box in your contact form. This involves two steps. The first step is to add a PHP library to your server that contains a lot of the reCAPTCHA functionality. Once you have done that, you then need to modify the HTML document your contact form is in by adding some inline PHP code that brings the reCAPTCHA code to life.

Upload recaptchalib.php

A part of the reCAPTCHA functionality actually lives on your server, so you need to download a single file from Google and then upload it. Go to the reCATPCHA Downloads page and download the latest PHP library.
Once you have downloaded the library, extract the contents to a location on your hard drive:




You'll see a handful of files, but the only one we care about is recaptchalib.php.
On your server, in the same directory as your contact form's HTML document or in a location that you can easily access from there, go ahead and upload this recaptchalib.php file.

Make Your Contact Form PHP Ready

Ok, do you remember when I said there are two steps needed to get the reCAPTCHA test to appear? Well, there are actually three steps. Just before you get to modify the HTML, you have to do one additional very important thing. The HTML document your contact form is living in needs to be able to run inline PHP scripts. If you don't know what that means, don't worry. Here is a simple test - does your contact form HTML document have a file extension of PHP? If so, you are set. Go ahead and skip over to the next section.
If your contact form page has an extension of HTM or HTML, rename the page to have an extension of PHP. For example, if you followed my contact form tutorial, you would rename contactform.htm tocontactform.php.

Note

If you are more knowledgeable with configuring your server, there are other ways of making an HTML document execute inline PHP content without renaming a page to have the PHP extension. The end result is what matters, so if you have your own ninja way of doing this, you should use it.
I am not a server wizard, so if you can share your technique, I (and others!) would appreciate it.

Displaying the reCAPTCHA Box...Finally

We are finally at the step that we've all been waiting for. It is time to actually display the reCAPTCHA test in our contact form. If you have friends and family around, call them over to look over your shoulder - that's how awesome this is going to be.

Credit Where Credit is Due

The snippets I provide in this section and the next are from Google's reCAPTCHA documentation with only very little modification by me.
If you haven't done so yet, open the HTML document containing the contact form, and find where your<form> element is. My contact form looks as follows:
<form action="mailer.php" method="POST">
    <div>
        <p>Name</p>
        <input name="name" type="text"> <br> </div>
    <div>
        <p>E-Mail (Optional)</p>
        <input name="email" type="text">
    <br>
    </div>
    <div>
        <br/>
        <input name="submit" type="submit" value="Send!">
    </div>
</form>
Inside your form, pick a location you want your reCAPTCHA test to appear, and add the following code:
<?php
    require_once('recaptchalib.php');
    $publickey = "<insert your public key>";
    echo recaptcha_get_html($publickey);
?>
In general, you want to have the reCAPTCHA test appear just above your Submit button. That's what I am going to do, so if you just want to follow along with my example, go ahead and add the highlighted code into your form:
<form action="mailer_recaptcha.php" method="POST">
    <div>
        <p>Name</p>
        <input name="name" type="text"> <br> </div>
    <div>
        <p>E-Mail (Optional)</p>
        <input name="email" type="text">
    <br>
    </div>
    <div>
        <p>Prove to me that you are not a spambot!</p>
        <br/>
        <?php
          require_once('recaptchalib.php');
          $publickey = "<insert your public key>";
          echo recaptcha_get_html($publickey);
        ?>
    </div>
    <div>
        <br/>
        <input name="submit" type="submit" value="Send!">
    </div>
</form>
Once you've added the PHP code in your contact form, let's look at it in greater detail to ensure you have everything setup correctly. The code we are going to be looking at is:
<?php
    require_once('recaptchalib.php');
    $publickey = "<insert your public key>";
    echo recaptcha_get_html($publickey);
?>
In the first line, you are making a call to the recaptchalib.php file. If that file isn't in the same directory as your contact page, make sure to update the path to the location the file is in.
The second line is important. For the $publickey variable, replace the values inside the quotation marks with the public key displayed in the reCAPTCHA Account Summary page. Don't use the private key here - you'll get a chance to use that shortly.
That's all there is to look at. If you preview your contact page right now, if everything worked out, you will see your normal form elements along with the reCAPTCHA box displayed:

If you are seeing something similar to what I am seeing, then you are almost done! The last thing to do is to modify the PHP script that receives this form data to validate what you placed into the reCAPTCHA form.

Validating the Words Entered

Right now, even though you see the reCAPTCHA box and can type things in, no validation is being done when you submit your form. You can type in complete jibberish and your form would submit just like it always has. Let's fix that in this section.
When you submit your form, the data your form contains will be sent to a PHP file. How this is done could look different depending on how your contact form is setup, but for the most part, like it is in my contact form, it will probably look like the following:
<form action="mailer.php" method="POST">
  // your actual contact form
</form>
Your form will have the action attribute set to the path of the PHP file that handles everything on the server. In the case of this contact form, that PHP file is mailer.php. It is in this file our code for validating the text typed into reCAPTCHA will be done.
Go ahead an open this PHP file. Once you have this PHP file opened, here is where things get a little lonely. You will need to modify the PHP yourself to ensure that your reCAPTCHA submission validates and your form data gets submitted. What I will provide is a basic PHP snippet that you will use to ensure the validation can happen. It is up to you to integrate the snippet with your existing form's functionality:

Don't worry. If you are somewhat familiar with PHP, you will have no difficulty at all. The snippet you need for verifying your form data will look as follows:
<?php
    if(isset($_POST['submit'])) {
     
        // check reCAPTCHA information
        require_once('recaptchalib.php');
         
        $privatekey = "< your private key>";
        $resp = recaptcha_check_answer ($privatekey,
                                    $_SERVER["REMOTE_ADDR"],
                                    $_POST["recaptcha_challenge_field"],
                                    $_POST["recaptcha_response_field"]);
         
        // if CAPTCHA is correctly entered!                       
        if ($resp->is_valid) {
            // great success!                   
        } else {
            // CAPTCHA entries are incorrect
        }
    }
?>
Just like before where you had to insert your public key, in the variable named $privatekey, provide theprivate key value that you have from your account summary. Make sure your private key is inside quotation marks.
Now, let's talk briefly about using this snippet as part of your contact form. My advice is for you to take this snippet in its entirety and then backport your existing PHP code for handling your form data to work inside it.
For the most part, your existing code will eventually end up living inside the following if statement:
if ($resp->is_valid) {
    // great success!                   
} else {
    // CAPTCHA entries are incorrect
}
The condition ($resp->is_valid) for this if statement evaluates to true if the data entered into the reCAPTCHA box checks out. Inside the true block, the one with the comment "great success!" is where your code for sending the form data will actually live. This code will be largely based on the existing code you may have had in this file before having to deal with the reCAPTCHA validation.
To give you an example, below is my revised mailer.php that takes the above validation snippet into account:
<?php
    if(isset($_POST['submit'])) {
     
        // check reCAPTCHA information
        require_once('recaptchalib.php');
         
        $privatekey = "< your private key>";
        $resp = recaptcha_check_answer ($privatekey,
                                    $_SERVER["REMOTE_ADDR"],
                                    $_POST["recaptcha_challenge_field"],
                                    $_POST["recaptcha_response_field"]);
         
        // if CAPTCHA is correctly entered!                       
        if ($resp->is_valid) {                       
            $to = "kirupa@kirupa.com";
            $subject = "reCAPTCHA Tutorial Submission";
             
            // data the visitor provided
            $name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING); 
            $email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
             
            //constructing the message       
            $body = " From: $name_field\n\n E-Mail: $email_field";
             
            // ...and away we go!
            mail($to, $subject, $body);
             
            // redirect to confirmation
            header('Location: confirmation.htm');
        } else {
            // handle the CAPTCHA being entered incorrectly
            header('Location: captcha_incorrect.htm');
        }
    } else {
        // handle the form submission error somehow
    }
?>
Notice that inside the if statement, all of the code for retrieving the data from my form fields as well as mailing that data can be found. The best part is that all of this code was just copied and pasted from what I had earlier.
If you test your contact form now, you'll see the behavior you defined for both correct as well as incorrect CAPTCHA entries. In my example, I navigate people either to a confirmation.htm page if the values are entered correctly or to captcha_incorrect.htm if the values are entered incorrectly. You can do whatever you want for either of these cases!
That's all there is to it.

Conclusion

Well, that is all there is to adding a reCAPTCHA test to a contact form. It isn't the most simple of things to do, but the payoff is well worth the effort. While there are some spambots that use good OCR (Optical Character Recognition) technology to decipher the text and pass the test, the vast majority fail the test very easily.
If you want some fun/background reading, read the reCAPTCHA Wikipedia page to learn more about its origins and how each time somebody fills out a reCAPTCHA form, they are helping digitize books, newspapers, and other non-digital things.

<div id="cancel-comment-reply">
<small>
</div>
<form action="http://www.wpfreeware.com/wp-comments-post.php" method="post" id="commentform">
<p>
<p>
<p>
<p>
<p>
<script type="text/javascript">
<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6LeW8PcSAAAAAAerX6vWbyJqNuiT5k8O0BCtecuO"/>
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha.js"/>
<div id="recaptcha_widget_div" class=" recaptcha_nothad_incorrect_sol recaptcha_isnot_showing_audio">
<noscript><iframe src="http://www.google.com/recaptcha/api/noscript?k=6LeW8PcSAAAAAAerX6vWbyJqNuiT5k8O0BCtecuO" height="300" width="500" frameborder="0"></iframe><br/> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/></noscript>
<div id="recaptcha-submit-btn-area">
<noscript><style type='text/css'>#submit {display:none;}</style> <input name="submit" type="submit" id="submit-alt" tabindex="6" value="Submit Comment"/></noscript>
<p class="comment-subscription-form">
<input type="checkbox" name="subscribe_comments" id="subscribe_comments" value="subscribe" style="width: auto; -webkit-appearance: checkbox;"/>
<label class="subscribe-label" id="subscribe-label" for="subscribe_comments">Notify me of follow-up comments by email.</label>
</p>
<p class="comment-subscription-form">
<input type="checkbox" name="subscribe_blog" id="subscribe_blog" value="subscribe" style="width: auto; -webkit-appearance: checkbox;"/>
<label class="subscribe-label" id="subscribe-blog-label" for="subscribe_blog">Notify me of new posts by email.</label>
</p>
</form>
</div>
</div>
</div>
<div class="more_themes">
<div style="clear: both; overflow: hidden; margin-top: 25px;"/>
<div class="more_themes">
</div>
<div class="fix sidebar floatright">
</div>
</div>






----------------------------------------------------------------------------------------------------------------------------------
READ MORE:
-------------------------------------------------------------------------------------------------------------------------------
http://www.kirupa.com/html5/adding_reCAPTCHA_to_a_contact_form.htm




0 comments:

Post a Comment

FB Gadgets | Template Designed by Fatakat PhotosCoolBThemes.com
Code by : paid web directory

https://www.google.co.uk/search?q=site%3Ablogspot.com+fbgadgets