Monday, March 25, 2013

A small neat PHP Captcha Script

I cannot stand the way some Captcha scripts look and work. Personally I give up very quickly when signing onto a web-service if I cannot 'identify' the Captcha characters easily. making hard for spider-bots is one thing, but making it impossible for humans is quite another.

So, here is a simple, clear captcha script written in PHP that makes it harder for bots to submit your forms, but obviously it not impenetrable (I would presume).

I have called it 'Matcha' to differentate it from other Captcha scripts (at least for us BlueBox-ers).

Invoke the Matcha session string at the top of your form like this:
  • $_SESSION["matcha"]=strtoupper(chr(65+rand(0,25)).chr(65+rand(0,25)).chr(65+rand(0,25)).chr(65+rand(0,25)).chr(65+rand(0,25)));
  • This will create a string of 5 uppercase A-Z characters.
In your form add these 2 rows to the layout:
  • <div class=cr_form_label>
    Characters to Match:
    </div>
    <div>
    <img src=\"<!--:class:bb_mymodule:matcha:-->\" >
    </div>

    <div class=cr_form_label>
    Enter Characters*:
    </div>
    <div>
    <input class=cr_form_field id=matcha name=global[matcha]>
    </div>
  • Remember to create a new BlueBox2.0 module called bb_mymodule (use the module name here, not this example name)
In the PHP BlueBox2.0 module (bb_mymodule) create a function as follows:
  • function matcha($err){
            global $global;
            $im = @imagecreatetruecolor(257, 36);
            $text_color = imagecolorallocate($im, 140, 140, 140);
            $white = imagecolorallocate($im, 255, 255, 255);
            imagefilledrectangle($im, 0, 0, 257, 36, $white);
            $font_file = 'portal/database_name/custom_modules/captcha.ttf';
            imagefttext($im, 15, 3, 70, 30, $text_color, $font_file, $_SESSION["matcha"]);
            imagepng($im,"portal/database_name/custom_modules/c/$_SESSION[matcha].jpg");
            imagedestroy($im);
            resp("portal/database_name/custom_modules/c/$_SESSION[matcha].jpg?".uniqid());
        }
  • You will need to upload a TTF font to the server that is suitably difficult to read for a bot-scanner.
 Finally, do a check when your form gets posted, to see if the entered amount matches the Matcha string:
  • if(strtoupper($global[matcha])!=$_SESSION[matcha]){
         resp("The characters you have entered do no match the string shown.");
         return;
    }

1 comment:

  1. Paulie, this is such a great idea. Whereas I have no clue as to what you have just written in computer code, I fully agree with the Captcha thing. I often have to try 3 or 4 times before I get one I can read. Hope to see your 'Matcha' option around more often:)
    Blessings
    D

    ReplyDelete