How to return to the redirect page after login (codeigniter)?

I have a login controller in my CI application:

function index()
{
    if($this->session->userdata('logged_in')==TRUE) 
        redirect('/success');

    $data['error']=$this->session->flashdata('errormessage');
    $this->load->view('auth',$data);
}

function process_login()
{

    $username=$this->input->post('username');
    $password=$this->input->post('password');

    if($password == "good_pwd")
    {
    $data=array('username'=>$username,'logged_in'=>TRUE);
    $this->session->set_userdata($data);
    redirect('/success');   
    }   
    else 
    {
        $this->session->set_flashdata('errormessage','Login failed');
        redirect('/failed');
    }
}

Here is my protective constructor in the main controller:

function __construct()
{
    parent::__construct();
    if($this->session->userdata('logged_in')!=TRUE)  redirect('/login');
}

When I try to get to www.mysite.com/main/function1/ and I have not logged in, then the designer redirects me to the login page - when I log in correctly, I am redirected to the main house instead of the page that redirected me to the login page (in this example: www.mysite.com/main/function1/) - how to do this?

+5
source share
2 answers

you need to save the request URI in the session for this so that you can return to the previous page, something like lines:

function __construct()
{
    parent::__construct();
    if($this->session->userdata('logged_in')!=TRUE) {
        $this->load->helper('url');
        $this->session->set_userdata('last_page', current_url());
        redirect('/login');
    }
}

... you can use session data to redirect back

+20

URL-

$redirect_to = "where you want to redirect after login";
$this->session->set_userdata('redirect_to',$redirect_to);

-

  $redirect_to = $this->input->post('redirect_to') ? $this->input->post('redirect_to') : $this->session->userdata('redirect_to');

    $this->template->build('login', array(
                '_user' => $user,
                'redirect_to' => $redirect_to,
            ));
0

All Articles