Simple and powerful captcha in PHP


example_form.php

<?php
    require_once(‘RainCaptcha.class.php’);
    $captcha = new RainCaptcha();
?>
<html>
<body>
<form action=”example_handler.php” method=”post”>
  <table>
    <tr>
      <th>Captcha</th>
      <td><img src=”<?php echo $captcha->getImage(); ?>” /> <br />
        <input name=”captcha” type=”text” maxlength=”5″ /></td>
    </tr>
    <tr>
      <td></td>
      <td><input type=”submit” value=”Submit” /></td>
    </tr>
  </table>
</form>
</body>
</html>

example_handler.php

<html>
    <body>
        <?php
            require_once(‘RainCaptcha.class.php’);
            $captcha = new RainCaptcha();

            if(isset($_REQUEST[‘captcha’])) {
                $isCaptchaCorrect = $captcha->checkAnswer($_REQUEST[‘captcha’]);

                if($isCaptchaCorrect) {
                    echo ‘You have entered <strong>correct</strong> CAPTCHA code!’;
                }
                else {
                    echo ‘You have entered <strong>wrong</strong> CAPTCHA code! <a href=”example_form.php”>Please try again!</a>’;
                }
            }
        ?>
    </body>
</html>

RainCaptcha.class.php

<?php
    /*
    ** RainCaptcha PHP module
    **
    ** Documentation: http://raincaptcha.driversworld.us/page/?page=docs_php_wrapper
    **
    ** This code is in the public domain.
    **
    ** Changelog:
    ** 2012-10-25 – Changed documentation URL.
    ** 2012-10-20 – Initial version.
    */
  
    class RainCaptcha {
        const HOST = ‘http://raincaptcha.driversworld.us‘;
        const CODE_LENGTH = 5;
      
        private $key;
      
        public function __construct($key = null) {
            if($key === null)
                $this->key = md5($_SERVER[‘SERVER_NAME’] . ‘:’ . $_SERVER[‘REMOTE_ADDR’]);
            else
                $this->key = $key;
        }
      
        public function getImage() {
            return self::HOST . ‘/captcha/?key=’ . $this->key . ‘&random=’ . rand(1000, 9999);
        }
      
        public function checkAnswer($code) {
            if(empty($code) || strlen($code) != self::CODE_LENGTH)
                return false;
            $apiResponse = file_get_contents(self::HOST . ‘/captcha/test/?key=’ . $this->key . ‘&code=’ . $code);
            if($apiResponse == ‘true’)
                return true;
            else
                return false;
        }
    }