I needed text based captcha for my mobile web application to stop automated registrations. The mobile application was developed targeting the WAP devices without any fancy JS or iFrame support. So, I was forced to put some text based captcha. I set one up earlier which didn’t require any database but it was just an eye wash. If anyone examined the HTML source, s/he would know how to break it through.
This time I have come up with something better, something more effective. It is quite simple. Have a look at the source code and you’ll understand yourself.
The SQL for the Table:
1 2 3 4 5 6 |
CREATE TABLE IF NOT EXISTS `masnun_text_captcha` ( `id` int(11) NOT NULL AUTO_INCREMENT, `captcha` varchar(255) NOT NULL, `time` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ; |
The TextCaptcha Class :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php class TextCaptcha { public function getCaptcha($id) { $res = mysql_fetch_assoc(mysql_query("select captcha from masnun_text_captcha where id='{$id}'")); return $res['captcha']; } public function verifyCaptcha($id,$captcha) { $captchaFromId = $this->getCaptcha($id); if ( !empty ( $captchaFromId ) && $captchaFromId == $captcha ) { mysql_query("delete from masnun_text_captcha where id='{$id}'"); return true; } else { return false; } } public function createNew() { $time = time(); $salt = "mZs45#"; $rand = rand(0,100); $hash = md5($time.$salt.$rand); $string = substr($hash, 0, 5); mysql_query("insert into masnun_text_captcha (captcha,time) values('$string','$time')"); $id = mysql_insert_id(); $data['id'] = $id; $data['captcha'] = $string; return (object) $data; } } ?> |
You might notice that I haven’t used the “time” field. It will be used to delete unused captcha via cron or in some other way. Didn’t get the time to code that.
And how to use it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php include 'textCaptcha.class.php'; // We must have an already open mysql connection to the database mysql_connect("localhost","masnun","masnun"); mysql_select_db("text_captcha"); $TextCaptcha = new TextCaptcha(); # Construct the object $captcha = $TextCaptcha->createNew(); # Create a new Captcha Object /* * The Captcha Object has two properties: * id --> The ID of the Captcha. You use it as an identifier. * captcha --> The Text that is matched with the id to verify * */ $bool = $TextCaptcha->verifyCaptcha($captcha->id, $captcha->captcha); var_dump($bool); // Always true :) Alter the code to play yourself ?> |
Have fun! If you don’t get anything, please place a question below.