How To Add BotDetect CAPTCHA Protection to PHP Forms

Protecting your PHP forms with BotDetect 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 Captcha("ExampleCaptcha");
  $ExampleCaptcha->UserInputID = "CaptchaCode";
  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:

Include BotDetect Files in the PHP Website

BotDetect 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 following to your PHP application's root folder:

  • the botdetect.php file from lib/botdetect.php
  • the whole botdetect folder from lib/botdetect

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

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 session_start(); ?>
<?php require("botdetect.php"); ?>

BotDetect requires PHP Session state to store Captcha codes, so you should ensure Session data is accessible before including BotDetect (or configure an alternate persistence mechanism). The second line then includes the BotDetect Captcha library.

Second, add the BotDetect layout stylesheet to ensure Captcha elements display correctly, usually just before the closing <head> tag:

  <link type="text/css" rel="Stylesheet" 
    href="<?php echo CaptchaUrls::LayoutStylesheetUrl() ?>" />
</head>

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 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 Captcha("ExampleCaptcha");
  $ExampleCaptcha->UserInputID = "CaptchaCode";
  echo $ExampleCaptcha->Html(); 
?>

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

The PHP code above creates a new instance of the Captcha 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 (e.g. "RegistrationCaptcha", "CommentCaptcha", ...) in the Captcha object constructor.

Validate Captcha User Input During PHP Form Submission

Since we want to ensure 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.

Form Has No Action

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 Captcha 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.

Separate Form Processing Action

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

session_start(); 
require("botdetect.php");

  […]

// Captcha validation 
$ExampleCaptcha = new Captcha("ExampleCaptcha");
$ExampleCaptcha->UserInputID = "CaptchaCode";
$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.