Number-only Captcha
November 22nd, 2009
Comments
I was recently looking for a Perl Captcha implementation that’d generate number-only Captchas. I looked inside Authen::Captcha and figured I could subclass it do just numeric captchas. It turned out to be a lot simpler than I thought it would be. Here is the code:
package Authen::NumCaptcha;
use strict;
use base qw(Authen::Captcha);
sub new {
my $class = shift;
my $captcha = $class->SUPER::new( @_ );
return bless $captcha, $class;
}
sub generate_random_string {
my $self = shift;
my $length = shift;
my $code = "";
my $char;
for (my $i=0; $i < $length; $i++) {
$char = int(rand 7)+50;
$char = chr($char);
$code .= $char;
}
return $code;
}
1;
We basically override Authen::Captcha's generate_random_string and only use ASCII characters 50 to 57 (digits 2 to 9). Authen::Captcha doesn't include the digits 0 and 1 because they could be confused with oh (O) and lower case elle (l) or upper case ai (I).
To use Authen::NumCaptcha, place it under /usr/share/perl5/Authen/ (or wherever you have Authen::Captcha installed) alongside Captcha.pm. Then use it as you'd use Auhten::Captcha. For example:
use Authen::NumCaptcha;
my $num_chars = 6;
my $num_captcha = Authen::NumCaptcha->new (
data_folder => '/tmp',
output_folder => '/tmp'
);
my $num_md5sum = $num_captcha->generate_code($num_chars);