How To Add BotDetect CAPTCHA Protection to PHP Forms

Protecting your PHP forms with BotDetect Simple PHP Captcha requires a few steps, outlined on this page. Displaying the Captcha challenge can be as simple as:

<?php // Adding BotDetect Captcha to the page 
  $ExampleCaptcha = new SimpleCaptcha("ExampleCaptcha");
  echo $ExampleCaptcha->Html(); 
?>

and checking user input when the form is submitted:

$isHuman = $ExampleCaptcha->Validate();

First Time Here?

Check the BotDetect PHP Captcha Quickstart for key integration steps.

You can also see how BotDetect Captcha protection has been added to various kinds of PHP forms and projects by running the BotDetect Captcha PHP integration code examples coming with the BotDetect installation. You can also reuse the code example source code that fits your requirements.

CAPTCHA Integration Steps

To add BotDetect Captcha protection to a PHP website:

1) Include BotDetect Files in the PHP Website

BotDetect Simple Captcha can simply be included in PHP websites by copying the Captcha library files from the BotDetect PHP download package.

You will need to copy the whole lib folder to your PHP application's root folder. It contains necessary components used to run Simple Captcha:

  • the simple-botdetect.php file
  • the whole botdetect folder
  • the config folder

We'll explain the details of individual Captcha library files later, and focus on the simplest way to use them for now.

2) Enable SQLite3

The SQLite3 extension is enabled by default as of PHP 5.3.0. Windows users must enable php_sqlite3.dll in order to use this extension.

BotDetect PHP Simple Captcha requires it to store Captcha codes, so you should ensure SQLite3 is enabled (or configure an alternate persistence mechanism).

3) Configure Captcha options

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/php"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://captcha.com/schema/php
     https://captcha.com/schema/php/botdetect-4.2.3.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>ExampleCaptcha</name>
      <userInputID>CaptchaCode</userInputID>
      <codeLength>3-5</codeLength>
    </captchaStyle>
  </captchaStyles>

</botdetect>

Configure Simple Captcha options in config/botdetect.xml configuration file. You can find a full list of available Simple Captcha configuration options and related instructions at the Simple Captcha configuration options page.

4) Display Captcha Protection on the PHP Form

We'll assume you already have a form which can be posted (<form method="post" ...), with other fields in place.

First, on the very top of the PHP form source file (before any other statements), add:

<?php require("lib/simple-botdetect.php"); ?>

To display the Captcha test on your form, you will need the following Html elements:

  • A textbox for the Captcha code user input, with a label displaying Captcha instructions. The name and id attributes must have the same value as <userInputID> tag in botdetect.xml.
  • The Captcha markup including the image, sound and reload icons etc., which will be generated by the Captcha library
For example:
<label for="CaptchaCode">Retype the characters from the picture:
</label>

<?php // Adding BotDetect Captcha to the page 
  $ExampleCaptcha = new SimpleCaptcha("ExampleCaptcha");
  echo $ExampleCaptcha->Html(); 
?>

<input name="CaptchaCode" id="CaptchaCode" type="text" />

The PHP code above creates a new instance of the SimpleCaptcha class defined by the BotDetect PHP Captcha library, tells it which textbox is used to input Captcha codes, and calls the Html function to generate all needed BotDetect Html elements.

When you open your form in a browser, the above declarations should render as:

BotDetect CAPTCHA added to an PHP page

If you are adding Captcha protection to multiple PHP forms in the same website, you should take care to give each one a unique name for each <captchaStyle> (e.g. "RegistrationCaptcha", "CommentCaptcha", ...) in the SimpleCaptcha object constructor. You can edit <captchaStyle> in botdetect.xml file.

5) Validate Captcha User Input During PHP Form Submission

Since we want to ensure that only real human users can perform a certain action (e.g. account registration or comment submission), we also have to add Captcha validation code which will process form submissions -- and only allow certain actions if Captcha validation succeeds.

Depending on if you post the form to the same or separate php file -- one of the following two things should be implemented:

  1. If Form Has No Action (form postbacks to the same PHP file)
  2. If Form Has Separate Form Processing Action (form postbacks to a separate PHP file)

a) If Form Has No Action (form postbacks to the same PHP file)

In the simplest case (when the form posts to itself, i.e. the action attribute is not set), you will process form submissions on the form itself:
<?php // when the form is submitted
  if ($_POST) { 
    // validate the Captcha to check we're not dealing with a bot
    $isHuman = $ExampleCaptcha->Validate();
    
    if (!$isHuman) {
      // Captcha validation failed, show error message
      echo "<span>Incorrect code</span>";
    } else {
      // Captcha validation passed, perform protected action
      // TODO
    } 
  }
?>

The above code is very simple:

  • The if ($_POST) { line ensures the code only runs when the form is submitted
  • The $isHuman = $ExampleCaptcha->Validate(); line calls the Validate() function of the SimpleCaptcha object, which returns true if the submitted Captcha code matches the one used for Captcha image generation, or false otherwise
  • Depending on the Captcha validation result, we either show a simple error message, or proceed with form submission processing.

This approach is shown in the BotDetect basic PHP integration code example included in the BotDetect download package.

b. If Form Has Separate Form Processing Action (form postbacks to a separate PHP file)

If your form posts to a separate .php file, you can use the same Captcha validation code, you just have to create a SimpleCaptcha object instance with the same name as the one used on the form first:

require("simple-botdetect.php");

  […]

// Captcha validation 
$ExampleCaptcha = new SimpleCaptcha("ExampleCaptcha");
$isHuman = $ExampleCaptcha->Validate();

if (!$isHuman) { 
  // Captcha validation failed, redirect back to form page
  header("Location: index.php?captchaValid=false");
  exit;
}

// TODO: continue with form submission
  

In this case, if the correct Captcha code wasn't submitted, we redirect the user back to the original form (adding a simple querystring for easier error reporting). You can also integrate the isHuman result with other form validation code, depending on your overall form validation approach.

In this trivial case, the form can then detect that it has been redirected back to with the querystring parameter and show a Captcha validation error to the user:

if (isset($_REQUEST['captchaValid']) && $_REQUEST['captchaValid'] == 'false') {
  // Captcha validation failed, show error message
  echo "<span class=\"incorrect\">Incorrect code</span>";
}

This approach is shown in the BotDetect PHP form integration code example included in the BotDetect download package.


Current BotDetect Versions