Redirect to previous page after logging in using PHP

php

Solution

You have three general approaches:

- Store the previous page in the session;

- Store the page as a GET variable; or

- Do an internal redirect to the login page.

(1) looks something like:

<?php
session_start();
if (!$_SESSION['userid']) {
  $_SESSION['page'] = '/contact';
  header('Location: /login');
  exit;
}
...
?>

On successful login retrieve `$_SESSION['page']` and redirect.

(2) is similar except there is no session variable. Instead you have:

header('Location: /login?return=/contact');

to pass the redirect. The login page will have to include it as a hidden form field on the page that presents the user with a request for the username and password.

(3) is similar but doesn't redirect to a separate page. Instead each page can potentially be a login page. If the user isn't logged in a login form is presented instead. The URL will still be "/contact". Each page will detect and handle log in attempts.

The advantage of this method is one less external redirect and it's easier to handle submitted forms. By this I mean that imagine someone fills out a form on one of your pages and then clicks submit. The system sees their login has expired. If you redirect the user to a new page and then redirect back they will probably need to re-enter all the form fields. If you handle the login implicitly you can include all the form fields as hidden inputs and once logged in seamlessly treat it as a submission of the original page.

Problem

Let's say I want to navigate to the contact page. But in order to get there, the site requires me to login. After logging in, I'm supposed to be redirected to the contact page, but I'm somewhere else. What should I do such that I should be redirected to the page I want after logging in? I have a strong feeling that this has something to do with sessions but nonetheless. What should the approach be?

Original source