Home > php教程 > php手册 > body text

The use of Session in ThinkPHP5

WBOY
Release: 2016-10-22 00:00:06
Original
1471 people have browsed it

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设置成功');
    }
}
Copy after login

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');
    }
}
Copy after login

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');
    }
}
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!