SoFunction
Updated on 2025-03-06

Example of Yii Framework Session and Cookie usage method

This article describes the use of Yii framework Session and cookies. Share it for your reference, as follows:

Yii Session Use

public function actionIndex(){
    $session = \YII::$app->session;
    //Judge whether the session is on    if(!$session->isActive) {
      //Not enabled, need to be enabled      $session->open();
    }
    //Set session    $session->set('user_name','zhangsan');
    //Get session    $user_name = $session->get('user_name');
    echo $user_name;
    //Delete session    $session->remove('user_name');
    //Array session    //Set session    $session['userName'] = 'lisi';
    //Get session    $user_name = $session['userName'];
    echo $user_name;
    //Delete session    unset($session['userName']);
}

Use of Yii cookies

public function actionIndex(){
    //Set cookies (note that the response component is used here)    $cookies = \YII::$app->response->cookies;
    $cookie_data = array('name'=>'user','value'=>'zhangsan');
    $cookies->add(new Cookie($cookie_data));
    //Get cookies (note that the request component is used here)    $cookie = \YII::$app->request->cookies;
    echo $cookie->getValue('user','default_value');//The second parameter is the default value when it does not exist    //Delete cookies (note that the response component is used here)    $cookies->remove('user');
}

For more information about Yii, readers who are interested in this site can view the topic:Yii framework introduction and common techniques summary》、《Summary of excellent development framework for php》、《Basic tutorial on getting started with smarty templates》、《PHP object-oriented programming tutorial》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.