Codeigniter Redirect Loop for user session is logg

2019-09-06 16:28发布

My controller

class Backspaze extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        session_start();
        $this->load->library('session');
        $this->load->model('getDB');
        $this->IsLogged();
}

function IsLogged()
    {
        if (!$this->session->userdata('id'))
            {
                 header('Location: '.base_url().'login');
         }

    }


function Login()
{


    $this->load->view('Auth/Login');
}

}

.htaccess

  RewriteBase /backspaze
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]

I almost tried all things which is available in internet the page gets redirect loop while checking for user is logged in, please give me some solutions

MY Config $config['uri_protocol'] = 'AUTO';

2条回答
Emotional °昔
2楼-- · 2019-09-06 17:09

Please check the following points

  • In your case, You should not check the session in constructor level. , Means, your controller consists of public & authenticated pages. So it will be looping/redirecting inside this controller only.

  • Move the session checking condition to the specific page and redirect to login page if suppose no session for authenticated pages. Below I have checked for user_details page which is I created for your understanding.

  • In your login method, you should check the already logged in or not and if yes, it should be go to dashboard page. I have created one method for that IsAlreadyLogged. please check it.

  • Don't add session_start() in your controller which will be take care of CI core

  • Use build-in redirect method which is CI core has

  • You should check session in constructor level if all pages are need to be authenticated in controller.

.

class Backspaze extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->model('getDB');
    }

    function IsLogged()
    {
        if (!$this->session->userdata('id'))
        {
            redirect('login');
        }
    }

    function IsAlreadyLogged()
    {
        if ($this->session->userdata('id'))
        {
            redirect('dashboard');
        }
    }

    function user_details()
    {
        $this->IsLogged();
        $this->load->view('user/details');
    }


    function Login()
    {
        $this->IsAlreadyLogged();
        $this->load->view('Auth/Login');
    }

}
查看更多
我想做一个坏孩纸
3楼-- · 2019-09-06 17:23

remove the line

session_start();

codeigniter handle it itself.
Replace this

header('Location: '.base_url().'login');

with

  redirect(base_url()."login");` 

but make sure you have loaded url helper

查看更多
登录 后发表回答