Redirect user back after login using CodeIgniter
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!