How can a page redirect users to the previous page if they try to access the page through a URL?

I have a login page that will not be available if the user is already logged in. Thus, the login page tries to redirect registered users to the page where they came from.

Redirecting works if users click on a link to go to a page. The problem is that users on the About page try to access the login page via the URL, then the referrer agent will not be installed, so the login page does not redirect users to the About page, instead it is redirected back to the base url (I use the codeigniter library and ion auth). Forwarding code to log in as shown below:

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

Is it possible to run this code and redirect correctly and not always redirect to the base url? When users register, I don’t show the link to the login page. This way, registered users can only go to the login page using the URL, and I want them to be redirected back to the page from where they came from.

+5
source share
4 answers

On the page that you want to return to you, you can do:

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

Then redirect back to this page

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

Try the following:

$this->load->library('user_agent'); redirect($this->agent->referrer());

yet

Use SESSION to log in and out. if the session exists, block the login page; still allow the login page using the if .

+4
source

I'm doing it.

redirect ($ _ SERVER ['HTTP_REFERER']);

+1
source

I don't know if there is a better way, but I always do this:

When the user is on the About page and clicks on the login, take the URL of the page, possibly base64_encode on it, and then send it to the login page via GET as a parameter. On the login page, if the credentials are valid, you take this parameter from GET, base64_decode and redirect there.

If you do this only for the main pages, you can only get the controller from the URL, but if you want to apply it on every page ( /controller/method/var1/var2 ), take the whole URL or the whole URL minus url code.

Let me know if this tip helped.

0
source

Source: https://habr.com/ru/post/1203891/


All Articles