Community Pick: Many members of our community have endorsed this article.
Editor's Choice: This article has been selected by our editors as an exceptional contribution.

Quickly get Captcha on your PHP site

Bruce SmithSoftware Engineer II
Published:
Updated:
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.
screen shot of CaptchaThe 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 />";
                                  }
                              }
                              ?>

Open in new window

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

Open 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
form.php
recaptchalib.php
success.php
4
5,662 Views
Bruce SmithSoftware Engineer II

Comments (2)

Commented:
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
Bruce SmithSoftware Engineer II

Author

Commented:
@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

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.