Parsing the cookies and session functions in the YII framework of PHP _php tips

Source: Internet
Author: User
Tags mongodb redis send cookies sessions yii

Sessions

Similar to requests and responses, the default is to access sessions by using the session application component for the Yii\web\session instance.

Open and Close Sessions

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

$session = Yii:: $app->session;

Check if session is open 
if ($session->isactive) ...

Open session
$session->open ();

Closes session
$session->close ();

Destroys all registered data in the session
$session->destroy ();

Calling the Yii\web\session::open () and Yii\web\session::close () methods multiple times does not produce an error, because the method internally checks to see if the session is open.

accessing session data

To access the "data stored in" session, you can do the following: Access the information in your session as follows:

$session = Yii:: $app->session;

Gets the value of the variable in 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 that the session variable already exists, the following usage is the same:
if ($session->has (' language ')) ...
if (Isset ($session [' language '])
... if (Isset ($_session[' language ')) ...

Iterate through all session variables, the following usage is the same:
foreach ($session as $name => $value) ...
foreach ($_session as $name => $value) ...

Add: When the session component is used to access the sessions data, it will automatically open if it is not turned on, unlike through $_session, $_session requires that the session_start () be executed first.
The session component restricts you from modifying the cell items in your data directly when the session data is an array, 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 also takes effect:
echo $session [' captcha '] [' lifetime '];

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

$session = Yii:: $app->session;

Direct use of $_session (ensure Yii:: $app->session->open () has been invoked)
$_session[' captcha ' [' number '] = 5;
$_session[' captcha ' [' lifetime '] = 3600;

First get 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 universal prefix to store the array
$session [' captcha.number '] = 5;
$session [' captcha.lifetime '] = 3600;

For better performance and readability, the last scenario is recommended, which is to not store the session variable as an array, but to turn each array item into a session variable with the same key prefix.

Customizing the Session Store

The Yii\web\session class defaults to storing session data as files to the server, and Yii provides the following sessions classes to implement a different method of Session storage:

    • Yii\web\dbsession: Storing session data in a datasheet
    • Yii\web\cachesession: Storing session data in cache, caching and configuration-related cache components
    • Yii\redis\session: Storing session data to 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 different session storage media does not require modifying the code for the project to use session.

Note: If you use a session with a custom storage medium through $_session access, you need to make sure that the session is already open with Yii\web\session::open () because the custom session storage processor is registered in the method.
Learn how to configure and use these component classes refer to their API documentation as an example of how to configure Yii\web\dbsession to use a data table as a session storage medium in an 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 datasheet 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 type of blob-type you choose for the database management system, 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, 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, will only work in the next request, and then the data is automatically deleted. It is often used to implement information that only needs to be displayed to end users once, such as when a user submits a form and displays a confirmation message.

You can use the session to set or access sessions by using the session, for example:

$session = Yii:: $app->session;

Request #1
//Set a name "postdeleted" Flash information
$session->setflash (' postdeleted ', ' You have successfully deleted Your post. ');

Request #2
//display named "postdeleted" Flash information
echo $session->getflash (' postdeleted ');

The request #3
//$result is false because the flash information has been automatically deleted
$result = $session->hasflash (' postdeleted ');

Similar to regular session data, you can store arbitrary data as flash data.

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

$session = Yii:: $app->session;

Request #1
//Add data to the Flash information named "Alerts"
$session->addflash (' Alerts ', ' You have successfully deleted post. ');
$session->addflash (' Alerts ', ' You have successfully added a new friend. ')
$session->addflash (' Alerts ', ' you are promoted. ');

Request #2
//$alerts for 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, but also use Yii\web\session::addflash (). Because the latter precaution automatically converts flash information to an array so that new flash data can be appended, when you call Yii\web\session::getflash (), you will find that sometimes you get an array, sometimes get a string, Depends on the order in which you call the two methods.
Cookies

Yii uses the Yii\web\cookie object to represent each cookie,yii\web\request and yii\web\response to maintain a collection of cookies through the properties named ' Cookies ', the former cookie A collection represents a request for a submitted cookie, which is a collection of cookies that are sent to the user.

Read Cookies

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

To get the cookie collection (yii\web\cookiecollection) from the request component
$cookies = Yii:: $app->request->cookies;

Gets the value named "Language" cookie, if it does not exist, returns the default value "en"
$language = $cookies->getvalue (' language ', ' en ');

Another way to get a value that is named "Language" cookies (
$cookie = $cookies->get (' language '))!== null) {
  $language = $cookie ; value;
}

You can use the $cookies as an array using the
if (isset ($cookies [' language '])) {
  $language = $cookies [' Language ']->value;
}

Determine if there is a cookie that is named "Language"
($cookies->has (' language ')) ...
if (Isset ($cookies [' language ']) ...

Send Cookies

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

Get the cookie Collection (yii\web\cookiecollection) from the "response" component
$cookies = Yii:: $app->response->cookies;

Add a new Cookie
$cookies->add ([
  ' name ' => ' language ',
  ' value ' => ') in the response to be sent. ZH-CN ',
]));

Deletes a cookie
$cookies->remove (' language ');
Equivalent to the following deletion code
unset ($cookies [' language ']);

In addition to the examples defined above, the Yii\web\cookie::name and Yii\web\cookie::value attributes Yii\web\cookie classes also define other properties to implement cookies of various information, such as Yii\web\cookie:: Domain, Yii\web\cookie::expire can configure these properties into cookies and add them to the cookie collection for the response.

Note: For security purposes yii\web\cookie::httponly is set to true, which reduces the risk of client script accessing protected cookies (if supported by browsers), and more details can be read HttpOnly wiki article for more Details.
Cookie Validation

In the last two sections, when you read and send cookies through the request and response components, you will enjoy the security features of the extended cookie validation, which allows cookies to be modified by the client. This feature notifies the server that the cookie is modified at the client by issuing a hash string to each cookie, and if it is modified, the cookie is not accessed 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 validation, the cookie can still be accessed through $_cookie because it is the Third-party Library's way of validating the customizations without the cookie.
Cookie authentication is enabled by default, you can set the Yii\web\request::enablecookievalidation property to False to disable it, however, we strongly recommend that it be enabled.

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

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

Add: Yii\web\request::cookievalidationkey is important to your application security and should only be known to people you trust, please do not put it in version control.

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.