ZENDFRAMEWORK2 Learning Note Verification code

Source: Internet
Author: User
Tags sessionstorage

ZF2 provides the picture verification code zend\captcha\image and the symbol character verification code Zend\captcha\figlet, the picture Verification code is the website application to see more a kind of verification code, this article takes the picture verification code as an example.

If you use the session to temporarily save the generated verification code, you need to configure the session first.

Parameter configuration for session:

/config/autoload/local.phpreturn Array ('    session ' = = Array ('        config ' = = Array (            ' class ' = ') ' Zend\session\config\sessionconfig ',            ' options ' = = Array (                ' name ' = ' = ' zf2ttttt ',            ),        ),        ' Storage ' = ' zend\session\storage\sessionarraystorage ',        ' validators ' = = Array (            ' zend\session\ Validator\remoteaddr ',            ' zend\session\validator\httpuseragent ',        ),)    ;

Application Call Session_Start after startup:

/module/application/module.phpnamespace Application;use Zend\mvc\moduleroutelistener;use Zend\Mvc\MvcEvent;use        Zend\session\sessionmanager;use zend\session\container;class module{Public Function onbootstrap (MvcEvent $e) {        $eventManager = $e->getapplication ()->geteventmanager ();        $moduleRouteListener = new Moduleroutelistener ();        $moduleRouteListener->attach ($eventManager); Sets the default language translator for form validation objects so that validation code validation does not pass when prompted by the default language user \zend\validator\abstractvalidator::setdefaulttranslator ($e->getap       Plication ()->getservicemanager ()->get (' translator '));    Start session $this->bootstrapsession ($e); The Public Function bootstrapsession ($e) {$session = $e->getapplication ()->getservicemanager ()->get (' Zend        \session\sessionmanager ');            $session->start ();                }//sessionmanager Factory Public Function Getserviceconfig () {return array (' factories ' = = Array ( ' Zend\Session\sessionmanager ' = function ($SM) {$config = $sm->get (' config ');                                                if (Isset ($config [' Session ')]) {$session = $config [' Session '];                        $sessionConfig = null; if (Isset ($session [' config '])) {$class = Isset ($session [' config '] [' class '])? $session [' Config ']                            [' class ']: ' Zend\session\config\sessionconfig '; $options = Isset ($session [' config '] [' options ']?                            $session [' config '] [' Options ']: Array ();                            $sessionConfig = new $class;                        $sessionConfig->setoptions ($options);                        } $sessionStorage = null;                            if (Isset ($session [' storage '])) {$class = $session [' storage '];                        $sessionStorage = new $class;} $sessionSaveHandler = null; if (Isset ($session [' Save_handler '])) {$sessionSaveHandler = $sm->get ($session [' Save_handler '                        ]); } $sessionManager = new SessionManager ($sessionConfig, $sessionStorage, $se                    Ssionsavehandler);                    } else {$sessionManager = new SessionManager ();                    } container::setdefaultmanager ($sessionManager);                return $sessionManager;    },            ),        ); }}

    Form form to add a verification code input: The verification code is a picture, you can use a text in the form to let the user enter a verification code, text next to display the CAPTCHA image:

/module/test/src/test/form/testform.phpnamespace Test\form;......use test\form\myimgcaptchavalidator;// Custom Verification Code Check class Testform extends Form implements inputfilterproviderinterface{... public function __construct ($            name = NULL) {...//Add the Captcha input box $this->add (' name ' = ' CV '),                            ' Type ' = ' Text ', ' options ' = = Array (' label ' = = ' Please enter the test code: ', ), ' attributes ' = = Array (' size ' = =, ' maxlength ' = 4,)        ,        ));    ......    } Public Function getinputfilterspecification () {...//Custom verification Code Check Object $captchaValidator = new        Myimgcaptchavalidator ();            .... return array (...). ' CV ' = = Array (' required ' + = True, ' filters ' = ' = ' Array (' n             Ame ' = ' Stringtrim '),       Array (' name ' = ' stringtolower '), ' validators ' = = Array ( Array (' name ' = = ' Notempty '), Array (' name ' = ' stringlength ',//This example will verify the code length                            Limit to 4 characters ' options ' = = Array (' encoding ' = ' UTF-8 ',                    ' min ' = 4, ' max ' = 4,    ), $captchaValidator,),); }}

Custom Verification Code Validation class:

/module/test/src/test/form/myimgcaptchavalidator.phpnamespace Test\form;use Zend\validator\abstractvalidator;  Use Zend\session\storage\sessionarraystorage;class Myimgcaptchavalidator extends Abstractvalidator {Const DIFFERENT =    ' Different '; Protected $messageTemplates = Array (self::D ifferent + "CAPTHCA inputted is DIFFERENT!",//Here is the string key if the language file is configured    The string, and sets the default Tranlaotr,validator base class for validator to automatically translate the string);                Public Function IsValid ($value) {$this->setvalue ($value);                $isValid = true;        $sessionKey _CAPTHCA = ' Sesscaptcha ';        $sessionStorage = new Sessionarraystorage ();        $captchaWord = $sessionStorage->offsetget ($sessionKey _CAPTHCA);//Get the session temporary saved verification code $WD = $captchaWord; if ($wd! = $value) {//Compare the input verification code and the generated CAPTCHA $this->error (self::D ifferent);//Incorrect input, set error message $isValid = FAL        Se    } return $isValid; }}

Output the CAPTCHA input box and the CAPTCHA image in the view:

/module/test/src/view/test/test/testform.phtmlecho ' <div> '; $captcha = $this->tform->get (' CV ');// Get the CAPTCHA input box table cell echo $formLabel->opentag (). $captcha->getoption (' label '); Echo $this->forminput ($captcha);// Show Verification Code input box echo ' </div> ';//display the Verification code picture, $IMGSRC for the controller transmitted echo $this->formelementerrors ($captcha);//Display error message echo $formLabel- >closetag (); Echo ' </div> ';

Controller code:

/module/test/src/test/controller/testcontroller.phpnamespace Test\controller;use Zend\Captcha\Image;use Zend\ Session\storage\sessionarraystorage;class TestController extends Abstractactioncontroller {public function Testformaction () {... if ($this->getrequest ()->ispost ()) {//user submits form, processes form data $postData = Array_merge_recursive ($this->getrequest ()->getpost ()->toarray (), $this->getre                        Quest ()->getfiles ()->toarray ());            $form->setdata ($postData);            if ($form->isvalid ()) {//form verification succeeded ...} ......        }                Session $sessionStorage = new Sessionarraystorage ();        Create verification code $sessionKey _CAPTHCA = ' Sesscaptcha '; $ICV = new \zend\captcha\image ();//zf2 only supports the generation of images in *.png format $ICV->setfont (' Public/fonts/arial.ttf ');//Specifies font files that can be selected from the window s system Folder "Windows\Fonts" to copy a "Arial.ttf" file into the/public/fonts directory $iCv->setfontsize (14);        $ICV->setheight (30);        $ICV->setwidth (80); $ICV->setdotnoiselevel (20);//Add pixel interference, default value is $ICV->setlinenoiselevel (2),//Add pixel line interference, default value 5 $ICV->setim Gdir (' public/captcha/');                                                    It is particularly important to note that the 2 parameters, Imgdir and Imgurl, are prone to problems where image files cannot be created or picture files cannot be displayed if they are not set up properly.                                                    The following collation sets and defaults for the 2 parameters://imgdir: The default value is Public/images/captcha.                                                    Imgurl: The default value is/IMAGES/CAPTHCA.                                                    As you can see, the default is to set the/public as the Web root by the Web site.                                                    Setimgdir: If it starts with the root character "/", it is considered an absolute path, for example, Setimgdir ('/public/captcha/'), then the picture is saved to/public/capthca/asdfas.png; If you do not start with the root character "/", the site root is the root and the value set is a subdirectory under the root directory of the Web site, for example, Setimgdir (' public/captcha/');              Save path to Webroot/public/capthca/asdfas.png (Webroot as Web site root);                                      Setimgurl: The root of the Web site root, for example, Setimgurl ('/public/captcha/'), if it starts with the root directory character "/", the image URL is http://x Xxx/public/capthca/asdfas.png;//If you do not start with the root symbol "/", the current route is the root , for example, if the current form URL is http://x/test/testform, then call Setimgurl (' public/captcha/'); the picture URL is http://x/test/public/capthca/ Asdfas.png;//To sum up, the correct way to set these 2 parameters is that the Setimgdir parameter "do not" start with "/", Setimgurl parameters "to                  Start with "/".        $ICV->setimgurl ('/public/captcha/');        $ICV->setwordlen (4);//Set the number of characters, the default is 8 characters//Create a new Captcha value $ICV->generate (); The URL of the captcha picture $IMGSRC = $ICV->getimgurl (). '        /'. $ICV->getid (). $ICV->getsuffix ();                The string of the captcha $captchaWord = $ICV->getword ();           The verification code is saved to session $sessionStorage->offsetset ($sessionKey _capthca, $captchaWord); Return Array (' tform ' = = $form, ' imgsrc ' = = $IMGSRC,//will verify the code Picture of UrL pass to view); }}

In addition, because the custom Authenticode validation class uses a string "CAPTHCA inputted is different!", it is necessary to configure the Chinese information of the string in the language file.

To add a language file configuration:

/module/test/config/module.config.phpreturn Array (...     ') Translator ' = = Array (        ' translation_files ' = = Array ('            type ' = ' = ' Phparray '     ,                ' FileName '  = = __dir__. '/.. /language/my_zh_cn.php ',//create your own language file my_zh_cn.php, save in/module/test/language/directory),),    ... );

To add a string to a language file:

/module/test/language/my_zh_cn.phpreturn Array (    "CAPTHCA inputted is different!" "+" Verification code entered incorrectly! ");

Sometimes, the verification code can not see clearly, you may need to click Refresh. To achieve the function of click Refresh, you can do some of the following changes to the above code.

The part of the controller that generates the verification code is cut out and placed in a function:

/module/test/src/test/controller/testcontroller.phpclass TestController extends Abstractactioncontroller {public        function Createcaptcha () {//Create verification code $sessionKey _CAPTHCA = ' Sesscaptcha '; $ICV = new \zend\captcha\image ();//zf2 only supports the generation of images in *.png format $ICV->setfont (' Public/fonts/arial.ttf ');//Specifies font files that can be selected from the window        s system Folder "Windows\Fonts" to copy a "Arial.ttf" file to the/public/fonts directory $ICV->setfontsize (14);        $ICV->setheight (30);        $ICV->setwidth (80); $ICV->setdotnoiselevel (20);//Add pixel interference, default value is $ICV->setlinenoiselevel (2),//Add pixel line interference, default value 5 $ICV->setim Gdir (' public/captcha/');                                                    It is particularly important to note that the 2 parameters, Imgdir and Imgurl, are prone to problems where image files cannot be created or picture files cannot be displayed if they are not set up properly.                                                    The following collation sets and defaults for the 2 parameters://imgdir: The default value is Public/images/captcha.                                                    Imgurl: The default value is/IMAGES/CAPTHCA. //visible, the default is to set/public to Web root according to the web site.                                                    Setimgdir: If it starts with the root character "/", it is considered an absolute path, for example, Setimgdir ('/public/captcha/'), then the picture is saved to/public/capthca/asdfas.png; If you do not start with the root character "/", the site root is the root and the value set is a subdirectory under the root directory of the Web site, for example, Setimgdir (' public/captcha/'); Save path to Webroot/public/capthca/asdfas.png (Webroot as Web site root);//setimgurl: If                                                    The root of the root directory, for example, Setimgurl ('/public/captcha/'), is the image URL is http://xxxx/public/capthca/asdfas.png; If it does not start with the root character "/", then the current route is the root, for example, assuming the current form URL is http://x/test/testform, then call Setimgurl ( ' public/captcha/'); the picture URL is http://x/test/public/capthca/asdfas.png;                  As described, the correct way to set these 2 parameters is that the Setimgdir parameter "do not" start with "/", the Setimgurl parameter "to" Start with "/".        $ICV->setimgurl ('/public/captcha/'); $ICV->setwordlen (4);//Set the number of characters, default is 8 characters//Create new validationThe value of the Code $ICV->generate (); The URL of the captcha picture $IMGSRC = $ICV->getimgurl (). '        /'. $ICV->getid (). $ICV->getsuffix ();                The string of the captcha $captchaWord = $ICV->getword ();        $sessionStorage = new Sessionarraystorage ();                   The verification code is saved to session $sessionStorage->offsetset ($sessionKey _capthca, $captchaWord);     return $IMGSRC; }}

Create a controller action that refreshes the CAPTCHA picture:

/module/test/src/test/controller/testcontroller.phpclass TestController extends Abstractactioncontroller {     Public Function refreshcaptchaaction () {         $IMGSRC = $this->createcaptcha ();         return new Jsonmodel (Array (             ' imgsrc ' = $imgSrc         )}     }

Add Refresh Captcha button to the view:

/module/test/view/test/test/testform.phtmlecho ' <div> '; $captcha = $this->tform->get (' CV '); echo $ Formlabel->opentag (). $captcha->getoption (' label '), Echo $this->forminput ($captcha); Echo ' </div> '; Echo $this->formelementerrors ($captcha); Echo $formLabel->closetag (); Echo ' <input type= ' Button "value=" refreshes "onclick=" Javascript:refreshcaptcha (); " /> '; Echo ' </div> ';

To add a client script that refreshes the CAPTCHA picture:

/module/test/view/test/test/testform.phtml<script>    function Refreshcaptcha () {    var ul = '/test/ Refreshcaptcha ';    Alert (UL);        $.ajax ({        type: "GET",        Url:ul,        dataType: "JSON",        success:function (data, Textstatus) {            $ ("# Imgcaptcha "). attr (" src ", data.imgsrc);                              },        error:function (R, T, R) {                                            }    }); </script>














ZENDFRAMEWORK2 Learning Note Verification code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.