您好,欢迎访问一九零五行业门户网

ThinkPHP5中Session的使用

由于用惯了thinkphp之前的版本,一想到要用session就直接用$_session来存取,今天看了thinkphp5的手册,才发现原来这么用时不安全滴。thinkphp5对session进行了封装,用的时候至少看起来安全多了。
session的设置
如果想要操作session,再think php5中需要使用think\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的读取
读取session最安全的方法是使用think\requet类的session方法
示例代码如下:
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变量。
当然也可以使用session类来读取session,不过这种方式最多只支持二维session变量的读取
示例代码:
namespace app\index\controller;use think\session;class user{ public function index() { echo session::get('user_name'); echo session::get('user.name'); }}
虽然有些麻烦,没有直接使用全局数组$_session存入session变量方便,但是为了安全,值得一试。
本文首发顶求网,转载请注明出处。
其它类似信息

推荐信息