CodeIgniter Forums

Full Version: How to redirect from initController?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello! I have the following code:

PHP Code:
<?php namespace App\Controllers\Admin;

use 
App\Controllers\BaseController;

abstract class 
AdminController extends BaseController
{
    protected 
$helpers = ['form'];

    public function 
initController(
        \
CodeIgniter\HTTP\RequestInterface $request,
        \
CodeIgniter\HTTP\ResponseInterface $response,
        \
Psr\Log\LoggerInterface $logger
    
) {
        
parent::initController($request$response$logger);
        
$user_id session()->get('user_id');
        if (empty(
$user_id))
        {
            return 
redirect()->route('home');
        }
    }


It do not work. How to do this type of authorization in CI 4?
im no expert but you had no replies. Is the essence of what you want to do is this:

if somebody is not logged in and tries to access a route they get sent back to home?

if so i have dome something similar . I have CI4 in dev but put it up live ; since i couldn't be bothered to set up SSl certificates for localhost. At https://www.benxmidia.com/usrLogin i have a simple
login page I get their name, password and entered captcha via the form which posts to a route.

All i do if name and password match name and hashed password in database and captcha is correct is set using a session in a controller: $_SESSION['role']="admin";

via a route called newblog
$routes->get('newblog', 'Blog::blogForm');

i display a form that gets the stuff i want to enter.I don't want anybody having access to that route unless they are logged in. I check that using a filter.

public function before(RequestInterface $request)
{
session_start();

$logic=isset($_SESSION['role']) ;
if($logic==false)
{
return redirect('usrLogin');

}


//as you can see if S_SESSION['role'] is either null or not set , any user trying to access my newblog gets brushed off back to login .

the instruction to check is via app/Config/Filters.php using

public $filters = [
'myfilter' => ['before' => ['newblog']],


];


probably i should check that $_SESSION['role'] is set that that it also equals admin, but its early days ,so also have not got around to csrf etc yet either!
Maybe should iniController stop the request if it return a response?
InitController was put in place so that it was simpler for people to use the controller's constructor without worrying about the framework. It wasn't intended to be a method that everyone used to do stuff in unless absolutely needed. So - no initController won't catch redirects. That's what filters or even the _remap method are for.