Sending a user back to the page they requested after login.

They have: 38 posts

Joined: Jun 2008

Hi all again, Im back for more!

I have been doing some google-ing but have not come up with anything useful yet, and I am not really sure what I should be google-ing for.

My problem this time is I need a way to send a user back to the page they clicked the "Login" link from. So when the view an article for example and they see login to submit a comment, they click login, login and then they are sent back to the article they were viewing.

I know this can be done I have seen it a million times, and quite frankly many more sites should do it, its so annoying to login and then be sent back to the index page.

Anyway, point me to another thread or link with this info if there is any, any help would be greatly appreciated.

Thanks all again,
Relentless.

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

The way I would do it is save a session of the URL they accessed (and then redirect them to the login page). Then, once they login, check if that session is set, and redirect them to the page.

So one some internal page, you would have something like:

if user is not logged in, then
   save current URL in session variable
   redirect the user to the login page
else
   show the page
endif

And on the login page you would have something like:

if the login form was submitted, then
  if the user's credentials are good, then
     if the session is set, then
        redirect user to URL saved in session
     endif
   else
      send the user to the regular page
   endif
else
  send the user back to the login page
endif
 

decibel.places's picture

He has: 1,494 posts

Joined: Jun 2008

If the login page is also the processing page, you could redirect to the referrer page

PHP: HTTP_REFERER

JavaScript: document.referrer

[note that REFERER in PHP has three "R"s while referrer in JS has four]

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

I would not recommend not using the referrer. Those can be spoofed, and browsers can even be configured to not send them. I use matt's method on all user-login sites I do.

decibel.places's picture

He has: 1,494 posts

Joined: Jun 2008

I would not recommend not using the referrer.

While your intended meaning is clear, your syntax encourages using referrer. Wink

[grammar police]

They have: 38 posts

Joined: Jun 2008

Thank you all very much, I will get to work and implement it. Will let you know what I did. Got to do some darn Uni work first though Sad

Peace.

Relentless.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.