ThinkPHP5中Session的使用

因为用惯了ThinkPHP以前的版本,一想到要用Session就直接用$_SESSION来存取,今天看了ThinkPHP5的手册,才发现原来这么用时不安全滴。ThinKPHP5对Session进行了封装,用的时候至少看起来安全多了。php

 

Session的设置数组

 

若是想要操做Session,再Think PHP5中须要使用Think\Session这个类安全

代码示例以下:session

namespace app\index\controller;
use think\Controller;
use think\Session;
class Index extends Controller{    
public function index()
    {        
        return $this->fetch();
    }    
    public function save($name='')
    {
        Session::set('user_name',$name);        
        $this->success('Session设置成功');
    }
}

 

Session的读取app

 

读取Session最安全的方法是使用Think\Requet类的session方法fetch

示例代码以下:this

namespace app\index\controller;
use think\Request;
class User
{    
    public function index(Request $request)
    {   echo $request->session('user_name');        // 读取二维数组
        echo $request->session('user.name');
    }
}

使用这种方式不只安全并且能够读取任意维度的Session变量。spa

固然也能够使用Session类来读取Session,不过这种方式最多只支持二维Session变量的读取.net

示例代码:get

namespace app\index\controller;
use think\Session;
class User{    
public function index()
    {        
        echo Session::get('user_name');        
        echo Session::get('user.name');
    }
}

虽然有些麻烦,没有直接使用全局数组$_SESSION存入session变量方便,可是为了安全,值得一试。

 

本文首发顶求网,转载请注明出处。

相关文章
相关标签/搜索