ThinkPHP5中Session的使用

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

 

Session的设置安全

 

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

代码示例以下:app

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的读取fetch

 

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

示例代码以下:spa

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变量。.net

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

示例代码:blog

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

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

相关文章
相关标签/搜索