Jan 23, 2008 15
How to implement reCAPTCHA
If you haven’t been spammed by bots, yet, you probably will soon be
.
On jobber.ro, we use reCAPTCHA to prevent spam. It’s a hosted captcha provider and much more!
Step 1. Create an account with reCAPTCHA
Go ahead and create an account, download the PHP API (and copy recaptchalib.php in the _includes/ directory, and sign up for an API key.
Step 2. Add reCAPTCHA when posting an ad
config.php
Define 2 constants, one for public and one for the private API key:
define('CAPTCHA_PUBLIC_KEY', '12345_YOUR_PUBLIC_KEY');
define('CAPTCHA_PRIVATE_KEY', '12345_YOUR_PRIVATE_KEY');
Also add the following line (find the other require_once lines), which includes the recaptcha library:
require_once '_includes/recaptchalib.php';
_templates/publish-write.tpl
Right above the submit button’s fieldset, insert the following code:
<h2 class="publish_section">Anti-spam</h2>
<fieldset>
{literal}
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'white',
tabindex : 9
};
</script>
{/literal}
{$the_captcha} <span class="validation-error">{if $errors.captcha}
<img src="{$BASE_URL}img/icon-delete.png" alt="" />{/if}</span>
</fieldset>
page-write.php
On line 2, we generate the html code that displays the captcha in the template:
$smarty->assign('the_captcha', recaptcha_get_html(CAPTCHA_PUBLIC_KEY));
Next, we perform a simple validation when posting the ad. Find the following line:
if ($_POST['action'] && $_POST['action'] == 'publish')
A couple of lines below it, after you initialize the $errors array, add this code:
$resp = recaptcha_check_answer(CAPTCHA_PRIVATE_KEY,
$_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid)
{
$errors['captcha'] = 'Incorrect code';
}
Then, we need to add the captcha validation in another section of page-write.php, the one that handles the ad edit. Find the following line and add the same code as above:
else if ($_POST['action'] && $_POST['action'] == 'edit'
That should be it
.
Enjoy!
