Adding captcha on PHP forms

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Continuing from our previous tutorial, in this tutorial we will add a captcha on our PHP form.  We will use the “Securimage” (spelled with no e) captcha from phpcaptcha.org.  To get the code, click Download Zip button on their GitHub repository.

A basic example that comes with the download is at “securimage/examples/static_captcha.php” and a more advanced one at securimage/example_form.ajax.php which shows ajax and audio captcha.

1.  Where your HTML form and your PHP processing file is, create a subfolder “securimage” and put the securimage content there.

2. To add the captcha to our form like this …

example captcha

example captcha

We have the following HTML.  We add the captcha image, the input box for the image, and the “a” link for new image …

HTML for securimage

HTML for securimage

Note that the src and other paths to the securimage subfolder may need to be adjusted per your situation.  The “a” link for new image is optional and can be safely omitted if you like.  They will get a new image when the page is refreshed anyways.

3. In your form processing PHP file add session_start() at the top and include the reference to securimage.php …

captcha processing PHP

captcha processing PHP

4.  Create new Securimage() class and call its check method.  If this method returns false, the code was not entered correctly.

The javascript:history.go(-1) returns user back to form page when they click the “try again” link.