lutego 06

Captacha w Zend Framework

Tag: Zend Framework, phpTI @ 06-02-2009 09:10
Bookmark and Share

Rozwiązanie to jest proste, wygodne i możliwe do zastosowanie w każdym formularzu.


Formularz

< ? $c = new TI_Captcha(); ?>
<input type="hidden" name="id" value="<?=$c-/>getId()?>">
<img src="<?=$c-/>getUrlImage()?>">
<input type="text" name="inputWord" value=""/>

Sprawdzenie

if(TI_Captcha::isValid($_POST["id"],$_POST["inputWord"])) {
	//wszystko się zgadza
} else {
	//nie zgadza się
}

Klasa która obsługuje całość

< ?php
class TI_Captcha {

	private $captcha = null;

	public function __construct($wordLen = 6, $width = 200, $height = 80, $noiseLevel = 300, $timeOut = 500, $pathToFont = "/application/models/TI/Font/FreeSansBold.ttf", $pathToImage = "/images/captcha") {
		$pathToFont = $_SERVER["DOCUMENT_ROOT"].$pathToFont;
		$pathToImage = $_SERVER["DOCUMENT_ROOT"].$pathToImage;

		if(!file_exists($pathToFont)) {
			throw new Zend_Exception($pathToFont." plik nie istnieje.");
		}
		if(!file_exists($pathToImage)) {
			throw new Zend_Exception($pathToImage." plik nie istnieje.");
		}		

		Zend_Loader::loadClass("Zend_Captcha_Image");
		$this->captcha = new Zend_Captcha_Image();

		$this->captcha->setTimeout($timeOut)
			->setWordLen($wordLen)
			->setHeight($height)
			->setWidth($width)
			->setDotNoiseLevel($noiseLevel)
			->setFont($pathToFont)
			->setImgDir($pathToImage);   

		$this->captcha->generate();
	}

	public function getId() {
		  return $this->captcha->getId();
	}

	public function getUrlImage() {
		return $this->captcha->getImgUrl().$this->captcha->getId().".png";
	}

	public static function isValid($id, $inputWord) {
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$captchaSession = new Zend_Session_Namespace("Zend_Form_Captcha_" . $id);
		$captchaIterator = $captchaSession->getIterator();
		$captchaWord = $captchaIterator["word"];

		if($captchaWord == $inputWord) {
			return true;
		} else {
			return false;
		}
	}

	public static function getWord($id) {
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$captchaSession = new Zend_Session_Namespace("Zend_Form_Captcha_" . $id);
		$captchaIterator = $captchaSession->getIterator();
		return $captchaIterator["word"];
	}
}
?>

Komentarz do “Captacha w Zend Framework”

  1. Jacek

    dzięki! najprostszy i najszybszy sposób na captcha :)

Zostaw komentarz

Podgląd komentarza: