会话管理用于Codeigniter中的重定向

I want to manage page redirection in codeigniter, I have two controllers:

  1. Logggedin
  2. login

When user try to access login page while he is logged in, he is redirected to Loggedin controller

function __construct()
{
    parent::__construct();
    $u = $this->session->userdata('username');

    if(! isset($u))
    {
        redirect('loggedin');
    }
}

And when he tries to access Loggedin controller while he is not logged in, he should be redirected to login controller

function __construct()
{
    parent::__construct();
    $u = $this->session->userdata('username');

    if(isset($u))
    {
        redirect('login');
    }
}

But when I press logout button, it has to redirect to Login controller, but he still remains on Logggedin controller.

function logout()
{
    $this->session->sess_destroy();
    redirect('login');
} 

What could be the problem in code?

In order to use codeigniter redirect function you must include the codeigniter url helper file, in which this function is actually written.

So, Load the codeigniter url helper file in your constructor

$this->load->helper('url');

and try by putting a '/' in front of the uri segment

redirect('/login');

Your redirect function is not working, as on logout, your session is destroyed, but the redirect is not taking place.

Your condition is always returning true

$u=$this->session->userdata('username');

// this is ALWAYS true because $u will equal the value from session or false
if(!isset($u))
{
  redirect('loggedin');
}

Instead, you should do this

$u=$this->session->userdata('username');
if( ! $u)
{
  redirect('loggedin');
}

The userdata method will return a boolean(false) if the data is not present.

From the Code Igniter Manual - Retrieving Session Data

Note: The function returns FALSE (boolean) if the item you are trying to access does not exist.