CodeIgniter Forums

Full Version: Redirect Not Working CI4
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Guys. I started a new Project with CI4 to see the new features and I am struggling trying to redirect between pages.

It's really simple...

I have a Login Controller

PHP Code:
<?php namespace App\Controllers;

use App\Models\Login_Model;

class Login extends BaseController
{

    protected $login_model;

    public function __construct()
    {
        $this->login_model = new Login_Model();
    }

    public function index()
    {
        echo view('login/templates/header');
        echo view('login/dashboard_view');
        echo view('login/templates/footer');
    


And a Dashboard Controller


PHP Code:
<?php namespace App\Controllers;

class Dashboard extends BaseController
{

    public function index()
    {
        echo view('admin/templates/header');
        echo view('admin/dashboard_view');
        echo view('admin/templates/footer');
    }






I would like to control the User Sessions. If the user is not log in on the system... Redirect to Login View.
I would like to have this functionality in all my Controllers so I just add it to the BaseController.

PHP Code:
    protected $session;
    
    public function initController
(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        
        $this
->session = \Config\Services::session();

        // User Access Control
        if (!isset($_SESSION['user_logged_in'])) {
            return redirect()->to(base_url('/login') );
        }


    


I tried everthing with (/), adding to routes of course. With only redirect(); A lot of things... but seems like something changes in CI4 that I dont get it.


SYSTEMPATH/HTTP\Exceptions\HTTPException.php
The only solution I found is move the Session Checker to the method Index of the Dashboard.

PHP Code:
<?php

namespace App
\Controllers;

class Dashboard extends BaseController
{

    public function index()
    {

        if (!(isset($_SESSION['user_logged_in']))) {

            return redirect()->to(base_url('public/login'));
            
        
} else {

            echo view('templates/header');
            echo view('dashboard_view');
            echo view('templates/footer');

        }
        
    
}


It's work in that way... but I will have to add this code to all index method in all my Controllers and I dont want that. I would like to have the Session Checker in the Base Controller so all Controllers will check the Session.

Any way that the redirect() works from BaseController?
(11-08-2019, 01:38 AM)Programaciones Web Wrote: [ -> ]It's work in that way... but I will have to add this code to all index method in all my Controllers and I dont want that. I would like to have the Session Checker in the Base Controller so all Controllers will check the Session.

Any way that the redirect() works from BaseController?

What you need is to use Controller Filters. They were designed for doing what you ask.
Still not working using filters... How do you do guys to redirect to login if user it's not logged without repeating condition in all Controllers::index?


PHP Code:
<?php

namespace App
\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

use CodeIgniter\Controller;
use CodeIgniter\Filters\FilterInterface;

class BaseController extends Controller implements FilterInterface
{

    protected $session;

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['session', 'url'];

    /**
     * Constructor.
     */
    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        $this->session = \Config\Services::session();

        if (!($this->session->has('user_logged_in'))) {

            return redirect()->to(base_url('public/login'));
            
        
}
    }


    public function before(\CodeIgniter\HTTP\RequestInterface $request)
    {
        return redirect('login');
    }

    public function after(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response)
    {
        return redirect('login');
    }


Quote:I tried everthing with (/), adding to routes of course. With only redirect(); A lot of things... but seems like something changes in CI4 that I dont get it.


SYSTEMPATH/HTTP\Exceptions\HTTPException.php


This worked for me. I created url_helper.php

url_helper.php then insert this code

PHP Code:
<?php

    
if (! function_exists('current_url'))
    {
        
/**
         * Current URL
         *
         * Returns the full URL (including segments) of the page where this
         * function is placed
         *
         * @param boolean $returnObject True to return an object instead of a strong
         *
         * @return string|\CodeIgniter\HTTP\URI
         */
        
function current_url(bool $returnObject false)
        {
            
$uri remove_host_http(\CodeIgniter\Config\Services::request()->uri);
            
            
$uri = (string) site_url($uri);

            
$uri $returnObject $uri remove_host_http($uri);

            return 
$uri;
        }
    }

    
//--------------------------------------------------------------------

    
if (! function_exists('remove_host_http'))
    {
        function 
remove_host_http($uri null)
        {
            
$uri str_replace('https://'$_SERVER['HTTP_HOST'].'/'''$uri);
            
$uri str_replace('http://'$_SERVER['HTTP_HOST'].'/'''$uri);

            return 
$uri;
        }
    }

    
//-------------------------------------------------------------------- 

And open the codeigniter.php replace storePreviousURL() method at line 978 with the code below

PHP Code:
public function storePreviousURL($uri)
    {
        
// Ignore CLI requests
        
if (is_cli())
        {
            return;
        }
        
// Ignore AJAX requests
        
if (method_exists($this->request'isAJAX') && $this->request->isAJAX())
        {
            return;
        }

        
// This is mainly needed during testing...
        
if (is_string($uri))
        {
            
$uri = new URI($uri);
        }
        
        
$uri str_replace('https://'$_SERVER['HTTP_HOST'].'/'''$uri);
        
$uri str_replace('http://'$_SERVER['HTTP_HOST'].'/'''$uri);
        
        
$uri = (string) site_url($uri);

        if (isset(
$_SESSION))
        {
            
$_SESSION['_ci_previous_url'] = (string) $uri;
        }
    } 

I hope this will help you solve your issue
There's an issue with the main url() commands that I'm trying to work out. This only happens when you're hosting in a subfolder or, like in your case, you're /public is part of your URL. It's intended that it gets served from the public directory so I never caught other cases. I imagine that's all of your issue here.

However, if you want to explore an app where auth is working, you can check out my in-progress forum software, which uses my Myth:Auth lib.
Also if you setup your base_url correct you do not need the / forward slash.