Welcome Guest, Not a member yet? Register   Sign In
Redirect Not Working CI4
#1

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
Reply
#2

I have same issue here:

https://forum.codeigniter.com/thread-74736.html
Reply
#3

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?
Reply
#4

(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.
Reply
#5

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');
    }


Reply
#6

(This post was last modified: 11-12-2019, 02:51 AM by Chivinsdev.)

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
Reply
#7

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.
Reply
#8

Also if you setup your base_url correct you do not need the / forward slash.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#9

Hi,

I'm trying to do the same thing with filters as suggested by Dave Friend, but even my initial experiments (to prove that the response can be messed with) of simply trying to override the return status code in an after filter isn't working.



Code:
class ExceptionFilter implements FilterInterface {

    public function before(RequestInterface $request) {
        // Do something here
    }

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

    public function after(RequestInterface $request, ResponseInterface $response) {

        $status_code = $response->getStatusCode();
        if ($status_code < 308) return $response;

        $response->setStatusCode(200, 'OK');   // $statusCodes[200] = 'OK'
        return $response;

I have the ENVIRONMENT=production for these tests (otherwise CI detailed exceptions get shown with a code trace). 

Could someone please explain this to me?

Thanks.
Reply
#10

(This post was last modified: 04-18-2020, 07:17 PM by Gary.)

Ok... so if I do this:

Code:
    public function after(RequestInterface $request, ResponseInterface $response) {

        $response->setStatusCode(201);
        $response->send();
        exit;

I get a reponse that is reported as a 201... however, the response body is lost- all I end up with is a blank document?!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB