由于用惯了thinkphp之前的版本,一想到要用session就直接用$_session来存取,今天看了thinkphp5的手册,才发现原来这么用时不安全滴。thinkphp5对session进行了封装,用的时候至少看起来安全多了。
Session的设置
如果想要操作Session,再Think PHP5中需要使用Think\Session这个类
立即学习“PHP免费学习笔记(深入)”;
代码示例如下:
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变量方便,但是为了安全,值得一试。
本文首发顶求网,转载请注明出处。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号