Not redirected to specific URL in Codeigniter 4

Certainly, if you want to perform a redirection in the constructor of a CodeIgniter 4 controller, you can use the header() method to set the location header and redirect to your desired controller. Here's your code rewritten with the header() method:

<?php namespace App\Controllers\Web\Auth;


class Register extends \App\Controllers\BaseController
{
    public function __construct()
    {
        parent::__construct();
        
        if (session()->has('username')) {
            header('Location: /dashboard');
            exit;
        }
    }


    public function index()
    {
        // Your controller logic here
    }
}


  1. We call parent::__construct(); to ensure that the constructor of the parent class (BaseController) is executed if necessary.
  2. We check if the 'username' session variable exists. If it does, we use header('Location: /dashboard'); to perform the redirection to the '/dashboard' route. We also call exit; to stop further execution of the script, ensuring that the redirection takes effect immediately.
  3. If the 'username' session variable does not exist, the constructor will continue executing, and you can place any other logic specific to the 'Register' controller in the index() method.

This code will redirect users to the '/dashboard' route if they have a 'username' session, and it allows you to perform additional controller-specific logic in the index() method when they don't have the session.

Sign In or Register to comment.