Thursday, January 13, 2011

Using recaptcha in PHP in localhost


Reference:
http://code.google.com/apis/recaptcha/docs/display.html
reCAPTCHA Library for PHP - v1.11 
reCAPTCHA quick start
A CAPTCHA is a program that can tell whether its user is a human or a computer. reCAPTCHA is a free CAPTCHA service.
1. go to
https://www.google.com/recaptcha/admin/create?app=php
type localhost (select  is not important here.)
click create key to get  public key and private key.
2. Download reCAPTCHA library, I put it under directory recaptcha-php-1.11 in my test directory
3. test_rec.html (replace the key after k= to your public key)
<html>
 <script type= "text/javascript">
    var RecaptchaOptions = {
    theme: 'clean'
    };
    </script>
  
    <body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
      <!-- your HTML content -->

      <form method="post" action="verify.php">
    
      <script type="text/javascript"
     src="http://www.google.com/recaptcha/api/challenge?k=6LcfdsASAAAAAIse5zmAapM1Tcx-xedplk6MjvBF">
  </script>
  <noscript>
     <iframe src="http://www.google.com/recaptcha/api/noscript?k=6LcfdsASAAAAAIse5zmAapM1Tcx-xedplk6MjvBF"
         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>
     
        <input type="submit" />
      </form>

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

4. verify.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
  require_once('recaptcha-php-1.11/recaptchalib.php');
    //localhost
  $privatekey = "6LcfdsASAAAAAPSluWN47bx8I_dwfYC_ggMx0gt9 ";
  $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 {
     echo " test successfully";
    // Your code here to handle a successful verification
  }
  ?>

5. A demo:




No comments:

Post a Comment