1/ Tạo form để nhập captcha:
Với captcha dạng hình ảnh, ta tạo thêm folder chứa hình ảnh /zfcaptcha/public/img/captcha và folder chứa font chữ phù hợp /zfcatcha/public/fonts/ten_font.ttf
Tạo form CaptchaImg.php trong /zfcaptcha/application/forms:
PHP Code:
<?php class Form_CaptchaImg extends Zend_Form{
public function init(){
$this->setAction('')->setMethod('post');
//Tạo captcha dạng hình ảnh, gồm 6 ký tự và có thời gian tồn tại là 300 giây
$captcha = new Zend_Form_Element_Captcha('captcha',array(
'label' => 'Captcha',
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 6,
'timeout' => 300,
'font' => APPLICATION_PATH.'/../public/fonts/tunga.ttf',
'imgDir' => APPLICATION_PATH.'/../public/img/captcha/',
'imgUrl' => '/zfcaptcha/public/img/captcha/',
'height' => 100,
'width' => 200,
'fontSize' => 50,
),
));
$submit = $this->createElement('submit','Submit');
$this->addElement($captcha)
->addElement($submit);
}
}Zend sẽ khởi tạo một captcha ID và chuỗi captcha . Chuỗi captcha này sẽ được lưu vào session với namespace là Zend_Form_Captcha_captchaID. Và do zend sử dụng session để lưu trữ nên trong file bootstrap.php ta thêm đoạn code sau:
PHP Code:
protected function _initSession(){
Zend_Session::start();
} Tạo file Captcha.php trong /zfcaptcha/application/forms/Validated/Captcha.php:
PHP Code:
<?php class Form_Validate_Captcha{
static function isValid($captcha){
$capId = $captcha['id'];
$capInput = $captcha['input'];
$capSession = new Zend_Session_Namespace('Zend_Form_Captcha_'.$capId);
$capWord = $capSession->getIterator();
if(isset($capWord['word']) && $capWord['word'] == $capInput){
return TRUE;
}else{
return FALSE;
}
}
}Tạo /zfcaptcha/application/controllers/CaptchaController.php:
PHP Code:
<?php class CaptchaController extends Zend_Controller_Action{
public function imageAction(){
$form = new Form_CaptchaImg;
if($this->_request->isPost()){
$captcha = $this->_request->getPost('captcha');
if(Form_Validate_Captcha::isValid($captcha)){
echo "Success";
}else{
echo "You're not human";
}
}
$this->view->form = $form;
//Đoạn code sau để xóa hình ảnh captcha sau khi xuất ra form
$mask = APPLICATION_PATH."/../public/img/captcha/*.png";
array_map("unlink",glob($mask));
}
PHP Code:
<?php echo $this->form; ?>Source mẫu zfcaptcha.rar
Không có nhận xét nào:
Đăng nhận xét