Parse related operations of cookie and session functions in PHP Yii Framework

Source: Internet
Author: User
Tags send cookies
This article mainly introduces the operations related to cookie and session functions in PHP Yii Framework. For more information, see Sessions

Similar to requests and responses, you can access sessions by default by using the Session application component of the yii \ web \ session instance.

Enable and disable Sessions

Use the following code to enable or disable a session.

$ Session = Yii: $ app-> session; // check whether the session is enabled if ($ session-> isActive )... // enable session $ session-> open (); // close session $ session-> close (); // destroy all registered data in the session $ session-> destroy ();

Multiple calls to the yii \ web \ Session: open () and yii \ web \ Session: close () methods do not produce errors, because the method first checks whether the session is enabled.

Access Session data

To access the data stored in session, you can do the following: you can use the following method To access data in the session:

$ Session = Yii: $ app-> session; // get the variable value in the session. the usage of $ language = $ session-> get ('language') is the same '); $ language = $ session ['language']; $ language = isset ($ _ SESSION ['language'])? $ _ SESSION ['language']: null; // you can specify a session variable. the usage of $ session-> set ('language ', 'en-use'); $ session ['language '] = 'en-use'; $ _ SESSION ['language'] = 'en-use '; // delete a session variable. the usage is the same: $ session-> remove ('language'); unset ($ session ['language']); unset ($ _ SESSION ['language']); // check whether the session variable already exists. the following usage is the same: if ($ session-> has ('language '))... if (isset ($ session ['language'])... if (isset ($ _ SESSION ['language'])... // traverse all session variables. the following uses the same: foreach ($ session as $ name => $ value )... foreach ($ _ SESSION as $ name => $ value )...

Supplement: when the session component is used to access the session data, it is automatically enabled if the session is not enabled. Unlike $ _ SESSION, $ _ SESSION requires that session_start () be executed first ().
When the session data is an array, the session component limits you to directly modify the unit items in the data, for example:

$ Session = Yii: $ app-> session; // The following code does not take effect: $ session ['captcha '] ['Number'] = 5; $ session ['captcha '] ['lifetime'] = 3600; // The following code takes effect: $ session ['captcha'] = ['Number' => 5, 'lifetime' => 3600,]; // The following code also takes effect: echo $ session ['captcha '] ['lifetime'];

You can use any of the following work s to solve this problem:

$ Session = Yii ::$ app-> session; // use $ _ SESSION directly (ensure that Yii: $ app-> session-> open () has been called) $ _ SESSION ['captcha '] ['Number'] = 5; $ _ SESSION ['captcha'] ['lifetime'] = 3600; // first obtain the session data to an array, modify the value of the array, and then save the array to the session $ captcha = $ session ['captcha ']; $ captcha ['Number'] = 5; $ captcha ['lifetime'] = 3600; $ session ['captcha '] = $ captcha; // use the ArrayObject array object instead of the array $ session ['captcha '] = new \ ArrayObject ;... $ session ['captcha '] ['Number'] = 5; $ session ['captcha'] ['lifetime'] = 3600; // use a key with a general prefix to store the array $ session ['captcha. number '] = 5; $ session ['captcha. lifetime'] = 3600;

For better performance and readability, we recommend the last solution, that is, to change each array item to a session variable with the same key prefix instead of storing the session variable as an array.

Custom Session storage

By default, yii \ web \ Session stores session data as files on the server. Yii provides the following session classes for different session storage methods:

  • Yii \ web \ DbSession: stores session data in the data table
  • Yii \ web \ CacheSession: stores session data in the cache. the cache is related to the cache component in the configuration.
  • Yii \ redis \ Session: stores session data to redis as the storage medium
  • Yii \ mongodb \ Session: stores session data to MongoDB.

All these session classes support the same API method set. Therefore, you do not need to modify the project session code to switch to different session storage media.

Note: If you use $ _ SESSION to access a session that uses a custom storage medium, make sure that the session has been enabled using yii \ web \ Session: open, this is because the custom session storage processor is registered in this method.
To learn how to configure and use these component classes, refer to their API documentation. the following example shows how to configure yii \ web \ DbSession in application configuration to use data tables as session storage media.

Return ['components' => ['session '=> ['class' => 'yii \ web \ DbSession', // 'DB' => 'mydb ', // ID of the application component connected to the database. the default value is 'DB '. // 'sessiontable' => 'My _ session', // session data table name. The default value is 'session'.],],];

You also need to create the following database tables to store session data:

CREATE TABLE session(  id CHAR(40) NOT NULL PRIMARY KEY,  expire INTEGER,  data BLOB)

'Blob 'corresponds to the BLOB-type of the database management system you selected, and the following BLOB types of common database management systems:

  • MySQL: LONGBLOB
  • PostgreSQL: BYTEA
  • MSSQL: BLOB

Note: According to session. hash_function set by php. ini, you need to adjust the length of the id column. for example, if session. hash_function = sha256, the char type should be 64 rather than 40.

Flash data

Flash data is a special session data. once it is set in a request, it will only be valid in the next request, and the data will be automatically deleted. It is often used to display the information only once to the end user. for example, the user submits a form and then displays the confirmation information.

You can set or access the session through the session application component, for example:

$ Session = Yii: $ app-> session; // request #1 // set a flash message named "postDeleted" $ session-> setFlash ('postdeleted ', 'You have successfully deleted your post. '); // request #2 // display the name "postDeleted" flash information echo $ session-> getFlash ('postdeleted '); // request #3 // $ result is false because the flash information has been automatically deleted. $ result = $ session-> hasFlash ('postdeleted ');

Similar to common session data, you can store any data as flash data.

When yii \ web \ Session: setFlash () is called, any existing data with the same name is automatically overwritten. to append the data to an existing flash with the same name, you can call yii \ web \ Session: addFlash (). For example:

$ Session = Yii: $ app-> session; // request #1 // add data in the flash information named "alerts" $ session-> addFlash ('alerts ', 'You have successfully deleted your post. '); $ session-> addFlash ('alerts', 'You have successfully added a new friend. '); $ session-> addFlash ('alerts', 'You are promoted. '); // request #2 // $ alerts is the flash information named 'alerts' in the array format $ alerts = $ session-> getFlash ('alerts ');

Note: Do not use yii \ web \ Session: setFlash () or yii \ web \ Session: addFlash () in flash data with the same name (), because the last precaution will automatically convert the flash information into an array so that new flash data can be appended, when you call yii \ web \ Session: getFlash, it will be found that sometimes an array is obtained, and sometimes a string is obtained, depending on the order in which you call the two methods.
Cookies

Yii uses yii \ web \ Cookie object to represent each cookie. yii \ web \ Request and yii \ web \ Response maintain a set of cookies through the property named 'cookies, the cookie set of the former indicates the cookies submitted by the request, and the cookie set of the latter indicates the cookies sent to the user.

Read Cookies

The cookie information of the current request can be obtained using the following code:

// Obtain the cookie set from the "request" component (yii \ web \ CookieCollection) $ cookies = Yii ::$ app-> request-> cookies; // obtain the value named "language" cookie. if the value does not exist, the default value "en" $ language = $ cookies-> getValue ('language', 'en') is returned '); // Another method is to obtain the value of "language" cookie if ($ cookie = $ cookies-> get ('language '))! = Null) {$ language = $ cookie-> value;} // you can use $ cookies as an array and use if (isset ($ cookies ['language']). {$ language = $ cookies ['language']-> value ;} // Determine whether cookieif ($ cookies-> has ('language') with the name "language" exists '))... if (isset ($ cookies ['language'])...

Send Cookies

You can send cookies to end users using the following code: You can use the following code to send cookies to end users:

// Obtain the cookie set from the "response" component (yii \ web \ CookieCollection) $ cookies = Yii ::$ app-> response-> cookies; // add a new cookie $ cookies-> add (new \ yii \ web \ Cookie (['name' => 'language ', 'value' => 'zh-cn',]); // delete a cookie $ cookies-> remove ('language '); // equivalent to the following code unset ($ cookies ['language']);

In addition to the yii \ web \ Cookie: name and yii \ web \ Cookie defined in the preceding example :: the value attribute yii \ web \ Cookie class also defines other attributes to implement various cookie information, such as yii \ web \ Cookie: domain, yii \ web \ Cookie :: expire can configure these attributes to the cookie and add them to the cookie set of the response.

Note: For security, yii \ web \ Cookie: httpOnly is set to true, which reduces the risk of client scripts accessing protected cookies (if supported by browsers, for more details, see httpOnly wiki article for more details.
Cookie verification

In the last two sections, when you use the request and response components to read and send cookies, you will enjoy the extended cookie verification security feature, which will prevent the cookies from being modified by the client. This function issues a hash string for each cookie to inform the server whether the cookie is modified on the client. if the cookie is modified, use the yii \ web \ request :: cookiescookie set cannot access this cookie.

Note: Cookie verification only protects the cookie value from being modified. if a cookie fails to be verified, you can still use $ _ COOKIE to access the cookie, this is a third-party library's custom operation method for failing to pass cookie verification.
Cookie verification is enabled by default. you can set the yii \ web \ Request: enableCookieValidation attribute to false to disable it. However, we strongly recommend that you enable it.

Note: Cookies READ and sent directly through $ _ COOKIE and setcookie () are not verified.
When cookie verification is used, you must specify the yii \ web \ Request: cookieValidationKey, which is used to generate the hash value above s. you can configure the request component in the application configuration.

return [  'components' => [    'request' => [      'cookieValidationKey' => 'fill in a secret key here',    ],  ],];

Supplement: yii \ web \ Request: cookieValidationKey is very important to your application security. it should only be known to people you trust. please do not put it into version control.

Related Article

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.