Since I am used to the previous version of ThinkPHP, when I want to use Session, I directly use $_SESSION to access it. I read the ThinkPHP5 manual today and found out that it is not safe to use it this way. ThinKPHP5 encapsulates the Session, which at least seems much safer when used.
Session settings
If you want to operate Session, you need to use the ThinkSession class in Think PHP5
The code example is as follows:
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 reading
The safest way to read a Session is to use the session method of the ThinkRequet class
The sample code is as follows:
namespace app\index\controller; use think\Request; class User { public function index(Request $request) { echo $request->session('user_name'); // 读取二维数组 echo $request->session('user.name'); } }
Using this method is not only safe but also allows you to read Session variables of any dimension.
Of course, you can also use the Session class to read the Session, but this method only supports reading of two-dimensional Session variables at most
Sample code:
namespace app\index\controller; use think\Session; class User{ public function index() { echo Session::get('user_name'); echo Session::get('user.name'); } }
Although it is a bit troublesome, it is not convenient to directly use the global array $_SESSION to store the session variable, but for safety, it is worth a try.
This article was first published on Dingqiu.com. Please indicate the source when reprinting.