Search code examples
phpcodeignitercodeigniter-4

How do I load a session in Codeigniter 4 Constructor


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


Solution

  • You need to initialize your session before calling session()->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 in 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
            }
    
    }
    

    And if you want to implement a filter, don't forget to declare it in 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'
            ],
        ];