Page 1 of 1

Avoid Junk Registrations using RECAPTCHA

Posted: Sun Jun 20, 2010 1:48 am
by tapan
hello ppl!!

mostly ur registration form is misused by BOTS, which enter fake registerations in ur account....this can be avoided by the use of Recaptcha....but the biggest trouble programmers face is inculcating the code downloaded with your forms...so i make an attempt to deal with the situation in steps. it involves maintaining sessions as well.


STEP 1

register your domain @ http://www.recaptcha.net

you will be provided with a public key and a private key....also u will be downloading a php file :- recaptchalib.php.....place this in the same directory as the registration form.


STEP 2

Code: Select all

i have added a sample code for a dummy form...u can change the fields as per ur requirement....let us name this file as "registration.php'

<?php session_start();
 if(isSet($_SESSION['msg']))
 {
    $msg = $_SESSION['msg'];
    unset($_SESSION['msg']);
 }
 else
     $msg = "";

?>

<html>
<head>
</head>
<body>
<?php echo $msg; ?>


     <form name="form" action="[b]FORMHANDLER.php[/b]" method="post"> // form action to FORMHANDLER.php 
	
      Full Name*	 <input type="text" name="name"  value = "<?php echo $_SESSION['name'];?>"   id="name" />
     // here the code for the recaptcha is initiated 
      <?php
      require_once('recaptchalib.php');// THE ONE YOU HAVE ADDED IN THE SAME DIRECTORY
      // Get a key from https://www.google.com/recaptcha/admin/create
      $publickey = ""; // enter your public key
      // Display the captcha field
      echo recaptcha_get_html($publickey, $error); //

?>

 <input type="submit" name="send" value="Send" />
</form>
</body>
</html>

<?php
unset($_SESSION['name']);
?>
Here goes the code for FORMHANDLER.PHP

Code: Select all

<?php 
session_start();
$_SESSION['name'] = $_REQUEST['name'];
ob_start(); // start output buffering. You might need this if you want to redirect to some page via header function.
require_once('recaptchalib.php');

// Get a key from https://www.google.com/recaptcha/admin/create
$publickey = "";
$privatekey = "your private key value goes here";

# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;

// get the captcha response via inbuilt function in recaptchalib.php

$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);

if ($resp->is_valid) 
{
            // your code if the captcha verification was successful
}
else
{       
                     $_SESSION['msg'] = "<span style = 'color: red;'>*Please fill in the correct image verification code</span>";
                     // redirect back to the registration  page.
                     header('location: http://example.com/registration.php');
                     ob_flush(); 
		     exit();
}
?>