php - How do I load a session in Codeigniter 4 Constructor
Get the solution ↓↓↓Just like in Codeigniter 3 where I can restrict users from a particular Controller if not on session by setting the below code in the Constructor
if(! session()->get('username'))
{
return redirect()->to('/login');
}
When I try the same in Codeigniter 4 it will not work, until I load this in each method before it works
Answer
Solution:
You need to initialize your session before callingsession()->get('yourvar')
.
This should work :
$session = session();
$session()->get('username');
However, as your post says, if you need to check on every Controller if they're in need of a session or not, you should definitely give a look at Filters and create a custom one that check if there's a session or not. https://codeigniter.com/user_guide/incoming/filters.html
It would probably look like this inapp/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');
}
}
//
And if you want to implement a filter, don't forget to declare it in{-code-5}
{-code-6}
Answer
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: regex stop at first match
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.