php教程

超轻量级php框架startmvc

Yii框架学习笔记之session与cookie简单操作示例

更新时间:2020-04-04 17:39:57 作者:startmvc
本文实例讲述了Yii框架学习笔记之session与cookie操作。分享给大家供大家参考,具体如下:se

本文实例讲述了Yii框架学习笔记之session与cookie操作。分享给大家供大家参考,具体如下:

session操作


<?php
 namespace app\controllers;
 use yii\web\Controller;
 class HelloController extends Controller{
    public function actionIndex(){
    //把session当做对象
    $session = \yii:$app->session;
   if($session->isActive){
    echo "session isactive";
   }else{
    $session->open();
   }
   $session->set("user","张三");
   $session->get("user");
   $session->remove("user");
    //把session当做数组 
    $session['user'] = "张三";
    unset($session["user"]);
    }
 }
?>

cookie操作


<?php
 namespace app\controllers;
 use yii\web\Controller;
 use yii\web\Cookie;
 class HelloController extends Controller{
 //存入cookie和修改cookie
 $cookies = \YII::$app->response->cookies; 
 $cookie_data = array('name'=>"user","value"=>"zhangsan");
 $cookies->add(new Cookie($cookie_data));//以'cookieValidationKey' 为基础的加密字符串
 $cookies->remove("id");//移除掉ID的cookie
 //取出cookie的值
 $cookies = \YII::$app->request->cookies;
 $cookies->getValue("user");
 //如果cookie不存在
 $cookies->getValue("user",20);//返回20
 }
?>

Yii框架 session cookie