Detailed Explanation of Method Examples of Yii Framework Operating cookie and session

  • 2021-12-21 04:30:09
  • OfStack

In this paper, an example is given to explain how Yii framework operates cookie and session. Share it for your reference, as follows:

cookie operation

Setting cookie


// Get response->cookies Component 
$cookies = \Yii::$app->response->cookies;
// Settings cookie Array 
$array_cookies=array('name'=>'user','value'=>'doubly');
// Add cookie Data 
$cookies->add(new Cookie($array_cookies));

Delete cookie


$cookies->remove('user');

Read cookie


$cookies = \Yii::$app->request->cookies;
echo $cookies->getValue("user");

Careful people may find that reading cookie is slightly different from the previous components, which are response->cookies While reading uses request->cookies Why is this? You can refer to the principle of saving cookie with response and reading cookie with request in the framework of Yii in the previous article

session operation

In the Yii framework for session operation, we are through a called session component things, first we need to get session component.


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

After obtaining the session component, to operate on session, we first need to determine whether session is enabled


if ($session->isActive){
  echo "session Has been opened ";
}else{
  $session->open();
}

After session has been turned on, we can set up and use session data. First, set up session data


$session->set("user"," Zhang 3");

Reading session data is also simple


$user = $session->get("user");

Similarly, there is deleting session data


$session->remove("user");

In addition, we can operate session as an array


// Settings session
$session['user'] = ' Zhang 3';
// Read session
$user = $session['user'];
// Delete session
unset($session['user']);

For more readers interested in Yii related contents, please check the topics on this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Yii framework.


Related articles: