由于用惯了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变量方便,但是为了安全,值得一试。
本文首发顶求网,转载请注明出处。