Using reCAPTCHA to stop spam in PHPreCAPTCHA helps prevent automated abuse of your site (such as comment spam or bogus registrations) by using a CAPTCHA to ensure that only humans perform certain actions.

You may have seen reCAPTCHA in use on many websites (including our forum) as it’s completely free and comes with an excellent web service which we are going to implement in this article.

The first thing to do is sign up to reCAPTCHA to receive your public and private key. These keys are used to authorize your account.

Next you need to download the reCAPTCHA library in PHP which can be found on this page. Once you have this you are ready to go.

First we are going to store the public and private key in variables, this would usually go in something like config.php.

<?php
include('recaptchalib.php');
$publickey = "…";
$privatekey = "…";

// Rest of your config goes here…
?>

Now on the page you want to display the CAPTCHA (e.g. register.php) you would include this at the top:

<?php
// Include the config file
include('config.php');

// If the form has been submitted
if (!empty($_POST)) {

  // Send the CAPTCHA results to reCAPTCHA
  $resp = recaptcha_check_answer ($privatekey, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);

  // Incorrect CAPTCHA?
  if (!$resp->is_valid) {
    $error = 'The reCAPTCHA was not entered correctly!';
  }

  else {
    // Otherwise continue with further validation etc
  }
}
?>

Now on the same page we display the actual CAPTCHA which is generated by the library so we don’t have to worry about any HTML or Javascript.

<form action="" method="post">
<!– Form fields would go here –>
<p><?php echo recaptcha_get_html($publickey); ?></p>
<p><input type="submit" name="submit" value="Complete Sign Up" /></p>
</form>