PHP Basic CAPTCHA Code Example

First Time Here?

Check the BotDetect PHP Captcha Quickstart for key integration steps.

The PHP Basic Captcha code example shows the most basic source code required to protect a PHP form with BotDetect CAPTCHA and validate the user input.

It can be used as a starting point when you are getting started with BotDetect.

Download the BotDetect PHP library and run this example

Within this page, the root folder of the extracted archive is referred as the <BDC-DIR>.

This example is in the <BDC-DIR>/examples/t_api-captcha-plainphp-api_basics/ folder; and contains the following files:

index.php

<?php session_start(); ?>
<?php require("botdetect.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>BotDetect PHP CAPTCHA Validation: Basic PHP CAPTCHA Code Example</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <link type="text/css" rel="Stylesheet" 
    href="<?php echo CaptchaUrls::LayoutStylesheetUrl() ?>" />
  <link type="text/css" rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
  <form method="post" action="" class="column" id="form1">

    <h1>BotDetect PHP CAPTCHA Validation: <br /> Basic PHP CAPTCHA Code Example</h1>

    <fieldset>
      <legend>PHP CAPTCHA validation</legend>
      <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();
      ?>

      <div class="validationDiv">
        <input name="CaptchaCode" type="text" id="CaptchaCode" />
        <input type="submit" name="ValidateCaptchaButton" 
          value="Validate" id="ValidateCaptchaButton" />

        <?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 class=\"incorrect\">Incorrect code</span>";
            } else {
              // Captcha validation passed, perform protected action
              echo "<span class=\"correct\">Correct code</span>";
            }
          }
        ?>
      </div>

    </fieldset>
  </form>
</body>
</html>

After including the BotDetect Captcha library, adding Captcha protection to the form is as simple as creating a Captcha object instance and printing the Html function result. The same object instance provides easy Captcha validation using the Validate function.