由於用慣了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變量方便,但是為了安全,值得一試。
本文首發頂求網,轉載請注明出處。
