0

how can I make redirection inside the constructor in the controller in Codeigniter 4? I made this code but doesn't work

function __construct()
{
    if(!isset($_SESSION['a']))
    {
        
         return redirect('index.php/login');
    }
}

1 Answers1

1

Two things here, one you shouldn't really be using the __construct magic method in codeigniter 4 Controllers. Instead you should use the initController method, like so:

public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
    parent::initController($request, $response, $logger);
}

The other thing you should look into is filters. A new feature introduced in Codeigniter 4 that serves the exact problem you just described.

You need to check something before or after a controller in run.

Here's an example on how to create a filter:

<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class CheckLogin implements FilterInterface
{

    /**
     * Check loggedIn to redirect page
     */
    public function before(RequestInterface $request, $arguments = null)
    {
        if(!isset($_SESSION['a'])) {
            return redirect()->to('/login');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do something here
    }
}

Then you should configure this in your app/config/Filter.php Her you should configure the alias and the controllers you want your filter to run:

public $aliases = [
    'csrf' => \CodeIgniter\Filters\CSRF::class,
    'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
    'honeypot' => \CodeIgniter\Filters\Honeypot::class,
    'checkLogin' => \App\Filters\CheckLogin::class,
];

public $filters = [
    'checkLogin' => ['before' => ['dashboard']],
];

In this case I'm using it in the dashboard controller but you can make it anything you want.

marcogmonteiro
  • 2,061
  • 1
  • 17
  • 26