简体   繁体   中英

Redirect loop in Codeigniter with single redirect from base controller

I have this base controller:

class TCMS_Controller extends  CI_Controller{
    public function __construct(){
        parent::__construct();
        if( ! $this->session->userdata('logged_in')){
            redirect('admin/authenticate/login');
        }
        //Loop to get all settings in the "globals" table
        foreach($this->Settings_model->get_global_settings() as $result){
            $this->global_data[$result->key] = $result->value;
        }
    }
}

So there I have this basic redirect:

redirect('admin/authenticate/login'); if user is not logged in.

Also I have this settings to remove index.php from urls:

.htaccess:

Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond ${REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

And next config settings:

$config['base_url'] = 'http://something.herokuapp.com/';
$config['index_page'] = '';

And when I'm trying to access admin section that has next address:

http://something.herokuapp.com/admin/controller/method

And if I'm not logged in, I supposed to be redirected to login page:

http://something.herokuapp.com/admin/authenticate/login

But instead i get a redirect loop

ERR_TOO_MANY_REDIRECTS

How do I fix it?

The page: http://tcms.herokuapp.com/

The admin section: http://tcms.herokuapp.com/admin/authenticate/login http://tcms.herokuapp.com/admin/dashobard

I am sure your admin (may be authenticate if admin is your folder name) controller also extends TCMS_Controller . So when it redirects your admin controller it executes TCMS_Controller 's construct function again and again redirect to admin controller which cause infinite loop.

To sovle this you need to make a Login controller which does not extends TCMS_Controller just extends CI_Controller.And redirect to this controller if user is not loged-in.

Well the problem that it's bad practice to have redirects in basic controller, because it can cause redirecting loops:

See: Codeigniter Redirect Loop for user session is logged in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM