How to Add Captcha in Php Form

Adding CAPTCHA to your form protects your site from spam bots. It is a program that generates colourful image with distorted text that human can read but current spam bots cannot figure out the text.

To add captcha to your php form, use reCaptcha. Your need to sign up to recaptcha using your google account. http://www.google.com/recaptcha

Go to my account and add your site. Once you have added your site, you will get the following details.

1) Public key

2) Private key

In addition, you need to get php recatpcha plugin from >> http://code.google.com/p/recaptcha/downloads/list?q=label:phplib-Latest

Once you have the Public key, Private key and recaptchalib.php file (Only this file is required for the recaptcha to work) from the plugin, you can start.

Add the following code in your client side form.

Client side code

require_once('recaptchalib.php');
  $publickey = "your_public_key"; // you got this from the signup page
  echo recaptcha_get_html($publickey);

How your code will look in a html form are shown below. Echo recaptcha_get_html($publickey) will print any errors when users enter the wrong password.

Client side with html form

<html>
    <body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
      <!-- your HTML content -->

      <form method="post" action="verify.php">
        <?php
          require_once('recaptchalib.php');
          $publickey = "your_public_key"; // you got this from the signup page
          echo recaptcha_get_html($publickey);
        ?>
        <input type="submit" />
      </form>

      <!-- more of your HTML content -->
    </body>
  </html>

Server side programming

Add the code below at the top of the verify.php file that the form post to. recaptcha_check_answer returns an object that represents whether the user successfully completed the challenge.

$resp->is_valid returns true when the user enters the correct answer and false when the input is wrong.

Server side programming

 <?php
  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 (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
    // Your code here to handle a successful verification
  }
  ?>

Another way to program at the server side.

Another way is to check the form variables are processed using $_POST and not $_REQUEST. In addition ensure that the form uses POST method.

You could create an error array to track any errors for any of the form inputs and process the form if there is no error. Another way to do. Please note the code below is not complete, you need to add your own verification and processing logic to make it complete, just adopt the method.

Another way, Server side programming

<?php


// For storing registration errors:
$registration_errors = array();



// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

// Require recaptcha config

  require_once('includes/recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,$_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"],   $_POST["recaptcha_response_field"]);



	// Check for a first name:
	if (preg_match ('/^[A-Z \'.-]{2,20}$/i', $_POST['first_name'])) {
		$fn = mysqli_real_escape_string ($dbc, $_POST['first_name']);
	} else {
		$registration_errors['first_name'] = 'Please enter your first name!';
	}
	
	
        if (!$resp->is_valid) {
                $registration_errors['captcha'] = 'Please enter correct captcha';
         
        }
  

	
	if (empty($registration_errors)) { 

         // process the form if there is no error. Add your processinf code here.
		
	} 

  

} // End of the main form submission conditional.

?>

You need to amend the html form if you use the just above method. To display the error just beside the recaptcha image.

 <html>
    <body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
      <!-- your HTML content -->

      <form method="post" action="verify.php">
        <?php
          if ($registration_errors['captcha']== 'Please enter correct captcha' ) {
              echo '<span class="error">'.$registration_errors['captcha'].'</span>' ;
          }
          require_once('recaptchalib.php');
          $publickey = "your_public_key"; // you got this from the signup page
          echo recaptcha_get_html($publickey);


        ?>
        <input type="submit" />
      </form>

      <!-- more of your HTML content -->
    </body>
  </html>

Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working