So you’ve made your CodeIgniter app using PHP, you’ve made is safe, secure and skipped needing to use SQL in favor of Active Records. Well the one thing most people forget to do (or realize later) is a simple UX (user experience) flow of post login routing.

Basically, you want users to go back to the content they viewed prior to login, in most cases this is the most preferred route because the user logs in so they can post, comment, or interact with something that might only be for logged in / registered users.

The easy way to handle this using CodeIgniter is to do a simple session save of the referring url like so:

In your login controller:

function index() {
    $this->load->library('user_agent');  // load user agent library
    // save the redirect_back data from referral url (where user first was prior to login)
    $this->session->set_userdata('redirect_back', $this->agent->referrer() );  
    ...
}

Then once you’ve authenticated your user, you can check if that value exists in session, and redirect them back to their original page, all seamlessly. Notice how I grab the redirect_back value into a temp var and remove the session variable (in case of it sticking for another redirect):

// user is authenticated, lets see if there is a redirect:
if( $this->session->userdata('redirect_back') ) {
    $redirect_url = $this->session->userdata('redirect_back');  // grab value and put into a temp variable so we unset the session value
    $this->session->unset_userdata('redirect_back');
    redirect( $redirect_url );
}

So there you have it, a simple flow for login and post-login redirection. Enjoy!



4 Comments to “Redirect user back after login using CodeIgniter”

  1. Aaron | March 10th, 2015 at 11:20 AM

    Thanks you help me on my work! thanks alot

  2. ritu | June 24th, 2016 at 2:14 AM

    dfgfghf

  3. gourab varma | September 7th, 2016 at 5:59 AM

    nice article

  4. irwan dwiyanto | February 9th, 2017 at 10:02 PM

    Woww…excellent thanks…

Leave a Comment