26-12-2011

PHP Zend Captcha image example

This is just a quick example of how you can deploy Zend Framework Captcha image component in a form.

This is the action inside the controller:

function turingtestAction(){
		if (isset($_POST['cid'])){	
			$capId = trim($_POST['cid']);
			$capSession = new Zend_Session_Namespace('Zend_Form_Captcha_'.$capId);
			if ($_POST['captcha'] == $capSession->word)
			{
				//succesful  test - probably a human
				$this->view->human = 1;
 
				return;  // end action execution here
			}
		} 
 
		$captcha = new Zend_Captcha_Image();
		$captcha->setImgDir(APPLICATION_PATH . '/../public/img/captcha/');
		$captcha->setImgUrl($this->view->baseUrl('/img/captcha/'));
		$captcha->setFont(APPLICATION_PATH . '/../public/css/LeagueGothic/League_Gothic-webfont.ttf');
		$captcha->setWordlen(5);
		$captcha->setFontSize(28);
		$captcha->setLineNoiseLevel(3);
		$captcha->setWidth(90);
		$captcha->setHeight(64);
		$captcha->generate();
		$this->view->captcha = $captcha;
}
 

This is the view code (turingtest.phtml):

<?php
if (isset($this->captcha)){ 
?><form method = "post" action = "<?= $this->baseUrl() ?>/auth/turingtest/">
	<input id="captcha" type="text" name="captcha" />
		<?php echo $this->captcha->render($this, null) ?>
	<input type="hidden" name="cid" value="<?php echo $this->captcha->getId() ?>" >
</form>
 
<?php 
}
if (isset($this->human)){ 
	echo  'human';
}?>
 
Keywords: captcha

Comments:

9 comments.
Your comment:

»
chirag 03/02/2012, 11:47 am
fine
Manish singh (s/w) 05/06/2012, 6:56 am
nice article form me......
thank from bottom of my heart..
Thukten 16/06/2012, 3:27 am
I tried to do the way you have given in your post...but i got the following error..can you please help me.

Warning: imageftbbox() [function.imageftbbox]: Invalid font filename in C:\xampp\htdocs\BICMA\library\Zend\Captcha\Image.php on line 489

Warning: imagefttext() [function.imagefttext]: Invalid font filename in C:\xampp\htdocs\BICMA\library\Zend\Captcha\Image.php on line 492...

thukten 16/06/2012, 3:36 am
I have solved the problem.....nice article
vadim 02/11/2012, 4:54 pm
As you have solved this problem
Qronicle 10/07/2012, 12:27 pm
You might want to add a check to see if your captcha session is still running, because when you resend this form, it will always go through:

if ($_POST['captcha'] == $capSession->word && $capSession->word)
Gopal Aggarwal 03/08/2012, 12:28 pm
Thanks a lot!
K313 08/11/2012, 9:27 am
http://k313.net/captcha.php?lang=2
cooljackd 07/02/2013, 12:54 pm
well nice example, but i would never use hidden fields not in this day and age.

 

[x]