Quickly get Captcha on your PHP site

AID: 3657
  • Status: Published

7540 points

  • Bypatsmitty
  • TypeTutorial
  • Posted on2010-09-03 at 23:12:43
Awards
  • Community Pick
  • Experts Exchange Approved

If you're like me and don't have tons of time to discover and implement new things/features on your website then you'll like this quick and easy example to keep automated bots from exploiting your web application forms. In just a couple of steps I'll walk you through on how to get the Captcha tool on your website.

captcha1.png
  • 15 KB
  • screen shot of Captcha
screen shot of Captcha


The beauty of Captcha is that it is free and requires virtually zero of your server space. Installation is as easy as a couple lines of code in your form's page and adding the captcha library php file to your directory. Then one simple if - then statement determines what the application should do depending on whether the user entered an appropriate captcha or not.

To get started head on over to http://www.google.com/recaptcha/whyrecaptcha to sign up (for free of course) and get your public and private keys (which you'll use in the next step). Once you're all signed up all you'll need is the recaptchalib.php file to put into your directory.

If you have successfully signed up and have the recaptchalib.php file and a private and public key you're ready to finish up.

First of all let's start with a simple php page (form.php) with a form that submits the inputted text on another page (success.php) if the captcha entry was valid; if not, then we show an error message below the captcha on the form page.

This example asks the user to input his favorite food and insert the Captcha. If the Captcha is correct, the user will be directed to a success page that shows his entry - otherwise an error message is displayed telling the user that the Captcha was entered incorrectly.

form.php

<form action="form.php" method="post">
            Favorite Food: <input type="text" id="favorite_food" name="favorite_food" value="" size="40" />
            <br /><br />
            <?php
            require_once('recaptchalib.php');
            $publickey = "your public key goes here...";
            $privatekey = "your private key goes here...";
            echo recaptcha_get_html($publickey, $error);
            ?>
            <br />
            <input type="submit" value="Submit" />
        </form>
        <br />
        <?php
        if ($_POST["favorite_food"]) { //checks to see if the form has been submitted
            $response = recaptcha_check_answer($privatekey, // captcha's function to validate input
                    $_SERVER["REMOTE_ADDR"],
                    $_POST["recaptcha_challenge_field"],
                    $_POST["recaptcha_response_field"]);
            if ($response->is_valid) {
                $fav_food = $_POST['favorite_food'];
                printf("<script>location.href='success.php?fav_food=$fav_food';</script>");
            } else {
                # set the error code in GREEN!
                echo "<p style='color: #95ca05; font-size: larger; font-family: 'tempus sans itc';>You entered the Captcha incorrectly.</p><br /><br />";
            }
        }
        ?>
                                  
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:

Select allOpen in new window


success.php

Your favorite food is: <?php echo($_GET['fav_food']);?>
                                  
1:

Select allOpen in new window


For this to work you need recaptchalib.php, form.php, and success.php to be in the same directory and your respective private and public keys set.

That's it, you can see how easy it is to determine what your web application will do when the captcha is correct or not. There are more customization options available if you check out http://code.google.com/apis/recaptcha/docs/customization.html and also there are 'PHP-less' solutions that I am not covering here: http://code.google.com/apis/recaptcha/docs/display.html.

If you want to see a working example of the example you can check it out here: http://www.patsmitty.com/captcha_tut/form.php

Also the source files are attached.

Cheers

Asked On
2010-09-03 at 23:12:43ID3657
Tags

PHP

,

captcha

,

javascript

,

recaptcha

Topic

PHP Scripting Language

Views
2324

Comments

Expert Comment

by: dspector on 2010-09-08 at 11:44:36ID: 19195

Image-based CAPTCHAs keep blind and visually impaired people out of your website or resource. Period. They are not fair, and someday will be illegal (since they violate the civil rights of an identified group of people).

Unless you are Yahoo! or similar, you won't have enough traffic to justify the use of an Image-based CAPTCHA, even ignoring the fairness angle. Why not use a text-based CAPTCHA? It is just as easy to add to your website, loads faster, doesn't discriminate against older folks who don't see so well, and lets people in quicker while baffling the limited logical capabilities of spammer's software.

I own a number of websites that use text-based CAPTCHA to submit Contact Us forms. I never have a problem with spam. Never. And my CAPTCHA is so simple: just copy three random digits into a text field. It can even be done by copy and paste. And if a spammer breaks it, all I have to do is change it a little. Add a digit, move the location of the field, almost any change keeps spammers out.

So simple, so fair.

David Spector

Author Comment

by: patsmitty on 2010-09-08 at 20:30:57ID: 19218

@dspector: You are correct that an image-based CAPTCHA disallows blind and/or visually impaired people from being able to use the website or resource. Thankfully, the good folks at reCAPTCHA (which is used in this example) have a workaround for impaired individuals - the option of an audio CAPTCHA challenge.

If you read the "Accessibility" piece in the "Guidelines" section at http://www.captcha.net/ you would see that these CAPTCHAs keep in mind the visually impaired and Section 508 in the United States.

Now, for your first comment about violating civil rights of an identified group, you are assuming the site is under the jurisdiction of the United States of America. Experts-Exchange has global members who write web-applications that may never fall under US jurisdiction thereby rendering the 'civil rights of an identified group' irrelevant.

Your second comment concerning not having enough traffic to justify usage of an image-based CAPTCHA is a statement showing a completely benighted idea of why a CAPTCHA is used. It makes no difference on how vulnerable a website is or isn't based on how much traffic a website generates. How about a form that takes user input and inserts it into a database? You could have a nightmare if a bot exploits that form by submitting thousands of records. Or how about a poll where users vote? It would lead to erroneous poll results.

"And if a spammer breaks it, all I have to do is change it a little." <shakes head> You have to be kidding right? If a spammer breaks it, depending on your web application, you may have to 'change it a little'... and then do a complete overhaul on your application's back-end! Just changing it a little doesn't fix the vulnerability or the damage done in the first attack.

With all respect,
     patsmitty

Add your Comment

Please Sign up or Log in to comment on this article.

Loading Advertisement...

Top PHP Experts

  1. Ray_Paseur

    317,680

    Wizard

    3,870 points yesterday

    Profile
    Rank: Savant
  2. Roads_Roads

    77,334

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  3. maeltar

    69,800

    Master

    4,200 points yesterday

    Profile
    Rank: Guru
  4. StingRaY

    67,254

    Master

    800 points yesterday

    Profile
    Rank: Wizard
  5. DaveBaldwin

    61,691

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  6. jason1178

    37,050

    0 points yesterday

    Profile
    Rank: Genius
  7. xterm

    28,850

    0 points yesterday

    Profile
    Rank: Sage
  8. COBOLdinosaur

    27,732

    0 points yesterday

    Profile
    Rank: Genius
  9. eriksmtka

    27,641

    2,000 points yesterday

    Profile
    Rank: Master
  10. smadeira

    26,150

    2,000 points yesterday

    Profile
    Rank: Guru
  11. webmatrixpune

    23,436

    2,000 points yesterday

    Profile
    Rank: Guru
  12. logudotcom

    19,588

    1,010 points yesterday

    Profile
    Rank: Genius
  13. bportlock

    17,470

    10 points yesterday

    Profile
    Rank: Genius
  14. Derokorian

    17,368

    0 points yesterday

    Profile
    Rank: Guru
  15. maestropsm

    16,698

    3,000 points yesterday

    Profile
    Rank: Master
  16. leakim971

    16,600

    0 points yesterday

    Profile
    Rank: Genius
  17. alex_code

    16,402

    0 points yesterday

    Profile
    Rank: Guru
  18. hernst42

    14,332

    0 points yesterday

    Profile
    Rank: Genius
  19. pratima_mcs

    14,200

    0 points yesterday

    Profile
    Rank: Genius
  20. Slick812

    13,900

    0 points yesterday

    Profile
    Rank: Sage
  21. elvin66

    12,628

    0 points yesterday

    Profile
    Rank: Wizard
  22. mwvisa1

    12,400

    0 points yesterday

    Profile
    Rank: Genius
  23. zappafan2k2

    12,200

    0 points yesterday

    Profile
    Rank: Guru
  24. TerryAtOpus

    11,600

    0 points yesterday

    Profile
    Rank: Genius
  25. amar_bardoliwala

    11,500

    0 points yesterday

    Profile
    Rank: Master

Hall Of Fame