how can a page redirect users back to previous page if they try to access the page via url?

user1906399 picture user1906399 · Oct 2, 2014 · Viewed 20.7k times · Source

I have a login page which won't be accessible if user is already logged in. So login page tries to redirect logged in users back to the page where they came from.

Redirect works if users click a link to go to a page. Problem is if users are in About page try to access login page via url then the referrer agent won't be set so login page is not redirecting users back to About page, instead it is redirecting back to the base url( i'm using codeigniter and ion auth library). login page's redirect code as below:

if($this->ion_auth->logged_in())
{
  redirect($this->agent->referrer(), 'refresh');
}

Is it possible to run this code and redirect properly instead of always redirecting to base url? When users are logged in i am not showing the link of the login page. So logged in users can only go to login page using url typing, and what i want is if they do they will be redirected back to the page where they came from.

Answer

westcoast picture westcoast · Nov 2, 2014

In the page that you want to go back to you can do:

$this->session->set_userdata('referred_from', current_url());

Then redirect back to that page

$referred_from = $this->session->userdata('referred_from');
redirect($referred_from, 'refresh');