How to redirect user to the viewing page before logging in

Let say I have 2 pages and one is called page A which is the index page and the other page B and assuming the user has to login to page B before he can post comment or click on like button and the user is being redirected from page B to the logging page, how can the user be redirected back to page B after logging. That is the user should be redirected automatically back to page B instead of page A which is the index page.

P.s. I will prefer it if example is in MVC pattern

You can redirect to another page using the header() function.

http://php.net/manual/en/function.header.php

What most systems do is record the URL that triggered the redirect to the login page in the session:

session_start();

if (!$loggedIn) {
    $_SESSION['return_url'] = get_current_url();
    header('Location: https://www.example.com/login');
}

(there is function get_current_url in PHP, you need to put your own mechanism here to obtain the current URL)

and then in the login page you would do

session_start();

if ($loginSuccessful) {
    header('Location: '.(isset($_SESSION['return_url']) ? $_SESSION['return_url'] : '/'));
}

You need to make sure to check the return_url value though before blindly redirecting to it, to avoid security exploits (for example check that it doesn’t start with http:// or https:// or when it does make sure it’s your own domain and not some external domain)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.