记住用户想要访问的页面

I have a few links on my page. Most of them will redirect to the homepage if the user is not logged in. Instead of doing that, I want to direct the user to the login page, then direct them to the page they originally wanted to go.

So, for example, if the user is on index.php, and clicks on page10.php without being logged in. S/he should get directed to login.php. After logging in, the website should remember that the user originally wanted to go to page10.php.

How do I do that remembering part? I understand I can use cookies and/or php sessions, but are those the most appropriate ways (in this scenario) of remembering that the user wanted to go to page10.php?

No need to use sessions or get variables, simply access the HTTP_REFERER from the $_SERVER array on your login page, set it to a hidden element in your form then after submission redirect back to that URI

Append desired URL as part of the link. So if a user is not logged in redirect him:

login.php?url=<desired_url>

read the variable on login page, and upon success direct it there instead of index.

To get the URL on the server side look at $_SERVER['REQUEST_URI']

$_SERVER manual

First, redirect to login.php?return=ORIGINAL_URL

In login.php set $_SESSION['return'] = $_GET['return'];.

After a successful login, check if there is a $_SESSION['return'], if there is, and is a valid URL, redirect to it and unset $_SESSION['return'].

That's it.

PS: The reason why you should use session is because the user may not login successfully on the first try. Or may not have an account, he may want to register first. This way he will be redirected to the appropriate page even after creating an account.

Logging a user in implies that you will be using sessions. Sessions usually use a cookie, but they can be implemented by passing a session id around in the request if you don't want to or can't use cookies.

The appropriate way to do this is to use sessions as follows:

1) The authentication check redirects to the login page

2) the login pages checks if the target page is set in the session and if it is not it sets it to the referrer

3) if the login form is valid the target page is removed from the session and the user is redirected to the original page

4) otherwise the form is redisplayed.