1 回答
TA贡献1803条经验 获得超3个赞
您需要在调用之前初始化您的会话session()->get('yourvar')
。
这应该工作:
$session = session(); $session()->get('username');
但是,正如您的帖子所说,如果您需要检查每个控制器是否需要会话,那么您绝对应该查看过滤器并创建一个自定义过滤器来检查是否存在会话。
它可能看起来像这样app/Filters
:
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class LoginFilter implements FilterInterface {
public function before(RequestInterface $request) {
$session = session();
if($session->has('username')) {
return redirect()->to('/login');
}
}
//--------------------------------------------------------------------
public function after(RequestInterface $request, ResponseInterface $response) {
// Do something here
}
}
如果你想实现一个过滤器,不要忘记在Config/Filters.php
// Makes reading things below nicer,
// and simpler to change out script that's used.
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
'login' => \App\Filters\LoginFilter::class,
];
// Always applied before every request
public $globals = [
'before' => [
'login',
//'honeypot'
],
'after' => [
'toolbar',
//'honeypot'
],
];
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报