Yii2.0 cookies mechanisms and how to use them

Source: Internet
Author: User
Tags exit in

In the actual project development process, the use of the Yii2.0 cookie mechanism! But encountered a very wonderful problem, the same yii framework, backend cookies can be stored normally in the client, but Frontend never. This question will be answered at the end of the article.

I. Verification mechanism of Yii2.0 cookies

Yii2.0 cookies are different from regular PHP cookie settings, yii2.0cookies use the cookie class to customize the name, value, expiration time, and then load the set up cookie configuration item into cookiecollection. Then the server side finishes processing the data submitted by the client and returns the triggering Yii:: $app the event in->response; Yii:: $app->response->send () method is invoked. Here's what the Send () method does:

     Public functionSend () {if($this-issent) {            return; }        $this->trigger (self::event_before_send); $this-prepare (); $this->trigger (self::event_after_prepare); $this-sendheaders (); $this-sendcontent (); $this->trigger (self::event_after_send); $this->issent =true; }

Among them, the $this->sendheaders () method contains the actual operation of the cookie, the method content is as follows:

    /** * Sends the response headers to the client*/    protected functionsendheaders () {if(headers_sent()) {            return; }        $statusCode=$this-Getstatuscode (); Header("http/{$this->version}$statusCode{$this->statustext} "); if($this-_headers) {            $headers=$this-getheaders (); foreach($headers  as $name=$values) {                $name=Str_replace(‘ ‘, ‘-‘,Ucwords(Str_replace(‘-‘, ‘ ‘,$name))); //set replace for first occurrence of headers but false afterwards to allow multiple                $replace=true; foreach($values  as $value) {                    Header("$name:$value",$replace); $replace=false; }            }        }        $this-sendcookies (); }

The $this->sendcookies () method in which it is invoked reads as follows:

    /** * Sends the cookies to the client. */    protected functionsendcookies () {if($this->_cookies = = =NULL) {            return; }        $request= Yii::$app-getrequest (); if($request-enablecookievalidation) {            if($request->cookievalidationkey = = "') {                Throw NewInvalidconfigexception (Get_class($request) . ':: Cookievalidationkey must is configured with a secret key. '); }            $validationKey=$request-Cookievalidationkey; }        foreach($this->getcookies () as $cookie) {            $value=$cookie-value; if($cookie->expire! = 1 &&isset($validationKey)) {                $value= Yii::$app->getsecurity ()->hashdata (Serialize($value),$validationKey); }            Setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie-httponly); }        $this->getcookies ()RemoveAll (); }

Here, I believe you have a new understanding of the Yii2.0 cookie mechanism!

Second, the specific use of Yii2.0 cookies

1. Add the following code to the main.php or main-local.php configuration file:

        ' Request ' = [            //  !!! Insert a secret key in the following (if it's empty)-this is require D by Cookie validation'            cookievalidationkey ' = ' fcuvvgfv0vex88qm5n2-h6hh5anm4hed ',        ],

2. Use the Yii2.0 cookie class to configure specific cookie parameters:

1        $rname 0=NewCookie ([2' Name ' = ' Rname_b ',3' Value ' = ' 1111111 ',4' Expire ' = Time() + 14400//Set expiration Time (one months)5                   ]);6        $ruser 0=NewCookie ([7' Name ' = ' Ruser_b ',8' Value ' = ' 2222222 ',9' Expire ' = Time() + 14400//Set expiration Time (one months)Ten]);

3. Call Yii:: $app->response->cookies instance to load the configured cookies into the cookiecolletion:

$resCookies = Yii::$app->response->cookies; $resCookies->add ($rname 0); $resCookies->add ($ruser 0);

At this point, the cookie-related configuration operation has been completed, the service end processing data to send the content to the client will trigger Yii:: $app->response event, will automatically write cookies into the client! is not very convenient Ah!

Back to the initial question, why did it appear so wonderful phenomenon? See what the difference is in the following code:

// "code One" the code that the cookie normally writes echo json_encode ($response, json_unescaped_unicode); // code "Two" cookies do not write properly echo json_encode ($response, json_unescaped_unicode); exit;

Because one more exit in the code causes the cookie to fail to write to the client. We understand the principle of YII2.0 cookies, I believe we all know the answer!

Yii2.0 cookies mechanisms and how to use them

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.