Parse PHP's YII framework for actions related to cookies and session functions, yiicookie_php Tutorial

Source: Internet
Author: User
Tags send cookies yii

Parsing PHP's YII framework for the operation of cookies and session functions, Yiicookie


Sessions

Similar to requests and responses, the default is to access sessions by applying components to the Session of the Yii\web\session instance.

Turning Sessions on and off

You can use the following code to turn session on and off.

$session = Yii:: $app->session;//Check if session is turned on if ($session->isactive) ...//open session$session->open ();// Close Session$session->close ();//Destroy all registered Data $session->destroy () in session;

Multiple calls to the Yii\web\session::open () and Yii\web\session::close () methods do not produce an error because the inside of the method checks whether the Session is turned on.

accessing session data

To access the data stored in session, you can do the following: The following methods can be used to access the information in the session:

$session = Yii:: $app->session;//Gets the value of the variable in the session, the following usage is the same: $language = $session->get (' language '); $language = $ session[' language '; $language = isset ($_session[' language '])? $_session[' language ': null;//set a SESSION variable, the following usage is the same: $session->set (' language ', ' en-us '); $session [' language '] = ' En-us '; $_session[' language '] = ' en-us ';//delete a SESSION variable, the following usage is the same: $session->remove (' language '); unset ($session [ ' language '); unset ($_session[' language '));//Check if 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 usage is the same: foreach ($session as $ name = $value) ... foreach ($_session as $name + $value) ...

Add: When using the session component to access session data, if the session does not open automatically open, which is different from $_session, $_session requires the first execution of Session_Start ().
When the session data is an array, the session component restricts you from directly modifying the cell items in the data, for example:

$session = Yii:: $app->session;//The following code will not take effect $session[' captcha ' [' number '] = 5; $session [' Captcha '] [' lifetime '] = 3600 ;//The following code will take effect: $session [' captcha '] = [  ' number ' + 5,  ' lifetime ' = 3600,];//The following code will also take effect: echo $session [' Captcha ' [' lifetime '];

You can use any of the following workarounds to resolve this problem:

$session = Yii:: $app->session;//directly using $_session (make sure Yii:: $app->session->open () has been called) $_session[' captcha ' [' Number '] = 5;$_session[' captcha ' [' lifetime '] = 3600;//First gets the session data to an array, modifies the value of the array, and then saves the array into the session $captcha = $session [' Captcha ']; $captcha [' number '] = 5; $captcha [' lifetime '] = 3600; $session [' captcha '] = $captcha;//use Arrayobject Array object instead of array $ session[' captcha ' = new \arrayobject; ... $session [' captcha '] [' number '] = 5; $session [' Captcha '] [' lifetime '] = 3600;// Use a key with a universal prefix to store the array $session[' captcha.number ' = 5; $session [' captcha.lifetime '] = 3600;

For better performance and readability, it is recommended that the last option 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 Store

Yii\web\session class default storage session data for the file to the server, YII provides the following session class to implement different session storage mode:

    • Yii\web\dbsession: Storing session data in a data table
    • Yii\web\cachesession: Store session data in cache, cache and cache components in configuration related
    • Yii\redis\session: Storing Session data in Redis as a storage medium
    • Yii\mongodb\session: Stores Session data to MongoDB.

All of these session classes support the same set of API methods, so switching to a different session storage medium does not require modifying the code for the project to use the session.

Note: If you access a session using custom storage media through $_session, you need to make sure that the session is turned on with Yii\web\session::open () 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 below for an example showing how to configure the Yii\web\dbsession data table as the session storage medium in the application configuration.

return [  ' components ' + = [    ' session ' + = '      class ' = ' yii\web\dbsession ',      /' db ' = ' mydb ', The application component ID of the database connection, which defaults to ' db '.      ' sessiontable ' = ' my_session ',//Session data table name, default to ' Session '.    ]  ;

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

CREATE TABLE session (  ID CHAR (+) not NULL PRIMARY KEY,  expire INTEGER,  data BLOB)

Where ' blob ' corresponds to the Blob-type type of the database management system you choose, the following are some common database management system BLOB types:

    • Mysql:longblob
    • Postgresql:bytea
    • Mssql:blob

Note: Depending on the session.hash_function set by php.ini, you need to adjust the length of the ID column, for example, if session.hash_function=sha256, you should use a char type of length 64 instead of 40.

Flash data

Flash data is a special session data that, once set in a request, is only valid for the next request, and the data is automatically deleted. It is commonly used to implement information that is displayed only once to the end user, such as when a user submits a form and displays a confirmation message.

Sessions can be set or accessed through the session application component, for example:

$session = Yii:: $app->session;//Request #1//Set up a flash message named "postdeleted" $session->setflash (' postdeleted ', ' you have Successfully deleted your post. '); /Request #2//display "postdeleted" Flash information echo $session->getflash (' postdeleted ');//Request #3//$result false, because flash information has been automatically deleted $ result = $session->hasflash (' postdeleted ');

Similar to normal session data, any data can be stored as flash data.

When you call Yii\web\session::setflash (), any data that already exists with the same name is automatically overwritten, and you can call Yii\web\session::addflash () instead to append the data to the same named Flash that already exists. For example:

$session = Yii:: $app->session;//Request #1//Add Data $session->addflash (' alerts ') to the Flash information named "Alerts" Successfully deleted your post. '); $session->addflash (' Alerts ', ' You have successfully added a new friend. '); $session->addflash (' Alerts ', ' You are promoted '); /Request #2//$alerts Flash information named ' Alerts ', array format $alerts = $session->getflash (' alerts ');

Note: Do not use Yii\web\session::setflash () in flash data of the same name and also use Yii\web\session::addflash (), Because the latter guard will automatically convert the flash information to an array so that the new flash data can be appended, when you call Yii\web\session::getflash (), you will find that sometimes you get to one of the arrays, sometimes get to a string, Depends on the order in which you call these two methods.
Cookies

Yii uses the Yii\web\cookie object to represent each cookie,yii\web\request and yii\web\response to maintain a cookie collection by using the attribute called ' cookies ', the cookie of the former The collection represents the cookies submitted by the request, and the latter's cookie collection represents the cookies sent to the user.

Read Cookies

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

Get a collection of cookies from the request component (yii\web\cookiecollection) $cookies = Yii:: $app->request->cookies;//Get the name "language" The value of the cookie, if it does not exist, returns the default value "en" $language = $cookies->getvalue (' language ', ' en ');//Another way to get the value named "Language" Cookie if (($ Cookie = $cookies->get (' language '))!== null) {  $language = $cookie->value;} The $cookies can be used as an array using if (Isset ($cookies [' language ')]) {  $language = $cookies [' Language ']->value;} Determine if there is a cookieif named "Language" ($cookies->has (' language ')) ... if (Isset ($cookies [' language ']) ...

Send Cookies

You can send a cookie to end users using the following code: The following codes can be used for sending cookies to the end user:

Get a collection of cookies from the "Response" component (yii\web\cookiecollection) $cookies = Yii:: $app->response->cookies;// Add a new Cookie$cookies->add to the response you want to send (\yii\web\cookie [  ' name ' = ' language ',  ' value ' = ' ZH-CN ',] );//delete a cookie$cookies->remove (' language ');//equivalent to the following delete code unset ($cookies [' language ']);

In addition to the Yii\web\cookie::name and Yii\web\cookie::value properties defined in the example above, the Yii\web\cookie class also defines other properties to implement various information about the Cookie, such as Yii\web\cookie:: Domain, Yii\web\cookie::expire can configure these attributes into a cookie and add it to the cookie collection of the response.

Note: For security reasons, Yii\web\cookie::httponly is set to true, which reduces the risk of client script accessing protected cookies (if browser support), more details can be read HttpOnly wiki article for more Details.
Cookie validation

In the previous two sections, when you read and send cookies through the request and response components, you would like the extended Cookie Authentication security feature, which allows cookies to not be modified by the client. This feature informs each cookie that a hash string is issued to the server to see if the cookie has been modified by the client and, if modified, is not accessible through the Yii\web\request::cookiescookie collection of the Request component.

Note: Cookie authentication only protects the cookie value from being modified, and if a cookie fails to authenticate, it can still be accessed through $_cookie because this is a third-party library's way of doing things that are not validated by cookies.
Although cookie validation is enabled by default, you can set the Yii\web\request::enablecookievalidation property to False to disable it, however, we strongly recommend enabling it.

Note: Cookies that are read and sent directly through $_cookie and Setcookie () are not verified.
When using cookie authentication, you must specify Yii\web\request::cookievalidationkey, which is used to generate the hash value described above, which can be configured by configuring the Request component in the application configuration.

return [  ' components ' + = ['    request ' = ' + ' cookievalidationkey ' + '      fill in a secret key here ',    ] ,  ],];

Add: Yii\web\request::cookievalidationkey is important to your app's security and should only be known to people you trust, so don't put it in version control.

Articles you may be interested in:

    • The definition and binding methods of behavior in the YII framework of PHP
    • A detailed approach to using behavioral behaviors in the PHP yii framework
    • In-depth explanation of properties in the Yii framework of PHP
    • Interpreting the process of request and response in the YII framework of PHP
    • PHP's YII framework uses database configuration and SQL Operations example tutorials
    • Examples of how to do error and exception handling in the PHP yii framework
    • A brief analysis of the basic knowledge of the modular mechanism of the YII framework of PHP
    • Examples of extensions to the Yiibase portal class in the PHP yii framework
    • The operation mechanism and routing function of the YII framework of PHP
    • In-depth parsing of event events mechanism in the YII framework of PHP
    • Full interpretation of the log function in the YII framework of PHP
    • The method of removing the binding behavior of a component in PHP's YII framework

http://www.bkjia.com/PHPjc/1111914.html www.bkjia.com true http://www.bkjia.com/PHPjc/1111914.html techarticle parsing PHP's YII framework for the operation of the cookie and session function, Yiicookie Sessions and the request and response similar, by default for the Yii\web\session instance of the session application component to visit ...

  • 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.