XHTML compliant reCaptcha

XHTML compliant reCaptcha

Introduction

Though I wrote my own captcha script a while back, I've wanted to deploy reCaptcha on my site for a while. The service is free and many major sites use it, including twitter. So, I signed up and downloaded the PHP library (in the plugin section, recaptchalib.php) and had a working version in a few minutes. If you want to deploy the service on your site, just sign up and follow the instructions on the website.

However, when I tested for compliancy, problems arose! After googling, I found that the service isn't XHTML compliant and that the developers had no intention of fixing it. So, if you want your site to be compliant with W3C's validator, you have to modify the PHP library provided by the reCaptcha dev team.

Modifying reCaptcha

To use the captcha service, you should be using a form and the captcha code should be within it like so:

<form id="FormMain" method="post" action="/contact">
<div>
<?php
    require_once('recaptchalib.php');
    $publickey = "Your_Public_reCaptcha_Key"; // you got this from the signup page
    echo recaptcha_get_html($publickey);
?>
<p><input name="btmSubmit" type="submit" value="Submit" /></p>
</div>
</form>

From this code, we can deduce that the function recaptcha_get_html() is called, and it resides in the recaptchalib php file. So if we open up that file and go to the function you should see the following code, within that function:

<noscript>
<iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" 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>';

The problem lies in the iframe as it is not correctly incorporated. So, we need to add a few things, including an object tag:

<noscript>
<div id="no_js_recaptcha">
<object type="text/html" data="http://api.recaptcha.net/noscript?k=' . $pubkey . '" width="500" height="300">
<!--[if IE]>
<iframe width="500" height="300" frameborder="0" src="http://api.recaptcha.net/noscript?k=' . $pubkey . '"></iframe> <![endif]-->
</object>
</div>
</noscript>';

Conclusion

Now save the code and you will have a compliant reCaptcha. Remember, the noscript tag is very picky about where it resides, this may also be giving you some errors, see this link.

Share