Using a custom CAPTCHA

I will explain briefly how to make a CAPTCHA field that will generate a random image, store the result using PHP sessions, then use an Quform validator to check if the entered result is correct.

  • 1. Create a PHP file that will generate the CAPTCHA image and store the expected result
  • 2. Change the existing CAPTCHA image to link to the PHP file above
  • 3. Customise the supplied CAPTCHA validator to check the submitted result against the expected result
  • 4. Add the CAPTCHA validator to the form element

Each step is explained in more detail below.

Step 1

Create a random CAPTCHA image using PHP and the GD image extension. There are many examples on the internet on how to do this, for example, Step 1 of this page. If you are using the code from that link, make sure to change the $_SESSION['digit'] part to $_SESSION['captcha'] and it will work seamlessly with Quform. Save the file as captcha.php

Step 2

Change the img src="" attribute of the existing CAPTCHA to point to your new captcha.php file.

Step 3

Open the file lib/Quform/Validator/Captcha.php an make sure the code looks to suit your requirements, e.g. your security code expected result is stored in $_SESSION['captcha']. You should also add <?php session_start(); ?> to the web page with your form on it, and also at the top of quform/process.php.

Step 4

In quform/process.php add the ‘captcha’ validator to your CAPTCHA element. The complete process.php code for the CAPTCHA element should be as below (assuming your unique name for the CAPTCHA element in the HTML is “captcha”):

1
2
3
4
5
6
$captcha = new Quform_Element('captcha', 'Type the characters');
$captcha->addFilter('trim');
$captcha->addValidator('required');
$captcha->addValidator('captcha');
$captcha->setIsHidden(true);
$form->addElement($captcha);
$captcha = new Quform_Element('captcha', 'Type the characters');
$captcha->addFilter('trim');
$captcha->addValidator('required');
$captcha->addValidator('captcha');
$captcha->setIsHidden(true);
$form->addElement($captcha);

The instructions are possibly too difficult for a novice web designer to do, so if that’s you then you should either stick with the basic CAPTCHA field or hire a professional web developer to set it up for you.

Still having trouble? Head over to the forums.

Forums